Android可不可以在子线程中更新UI?

关于这个问题在面试的时候可能会被问到,其实在某些情况下是可以在子线程中更新UI的!

比如:在一个activity的xml文件中中随便写一个TextView文本控件,然后在Activity的onCreate方法中开启一个子线程并在该子线程的run方法中更新TextView文本控件,你会发现根本没有任何问题。

private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.threadcrashui_act);
    textView = (TextView) findViewById(R.id.textView);
    new Thread(new Runnable() {
        @Override
        public void run() {
            // 更新TextView文本内容
            textView.setText("update TextView");
        }
    }).start();
}
Paste_Image.png

但是如果你让子线程休眠2秒钟如下面代码:

private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.threadcrashui_act);
    textView = (TextView) findViewById(R.id.textView);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                //更新TextView文本内容
                textView.setText("update TextView");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
Paste_Image.png

程序直接挂掉了,好吧,我们先去看看log日志,如图提示
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
程序不允许在非UI线程中更新UI线程

Paste_Image.png
对于这个问题,可能大家都跟我一样有点疑惑对吧?我当时也很疑惑,不明白为啥是这样!!!然后我去翻资料查找原因,最终定位到setText这个方法
  /**
 * Sets the string value of the TextView. TextView <em>does not</em> accept
 * HTML-like formatting, which you can do with text strings in XML resource files.
 * To style your strings, attach android.text.style.* objects to a
 * {@link android.text.SpannableString SpannableString}, or see the
 * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">
 * Available Resource Types</a> documentation for an example of setting
 * formatted text in the XML resource file.
 *
 * @attr ref android.R.styleable#TextView_text
 */
@android.view.RemotableViewMethod
public final void setText(CharSequence text) {
    setText(text, mBufferType);
}
紧接着看setText方法
   /**
 * Sets the text that this TextView is to display (see
 * {@link #setText(CharSequence)}) and also sets whether it is stored
 * in a styleable/spannable buffer and whether it is editable.
 *
 * @attr ref android.R.styleable#TextView_text
 * @attr ref android.R.styleable#TextView_bufferType
 */
public void setText(CharSequence text, BufferType type) {
    setText(text, type, true, 0);
    if (mCharWrapper != null) {
        mCharWrapper.mChars = null;
    }
}
再进setText方法
private void setText(CharSequence text, BufferType type,
                     boolean notifyBefore, int oldlen) {
  //前边的都省略掉 .......
    if (mLayout != null) {
    //这个方法的作用就是让界面重新绘制下
        checkForRelayout();
    }
   //后边的也直接省略掉

}

然后我们看下checkForRelayout方法,在这里大家会看到一个invalidate的方法,因为我们知道所有的view更新操作都会调用view的invalidate方法!那么问题就在这里了
/**
 * Check whether entirely new text requires a new view layout
 * or merely a new text layout.
 */
private void checkForRelayout() {
       //注意看这里
        invalidate();
    } else {
       //注意看这里
        invalidate();
    }
}
然后我们进invalidate方法中查找原因
/**
 * Invalidate the whole view. If the view is visible,
 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
 * the future.
 * <p>
 * This must be called from a UI thread. To call from a non-UI thread, call
 * {@link #postInvalidate()}.
 */
public void invalidate() {
    invalidate(true);
}
好 那么我们就看下invalidate(true)方法看看到底是哪的问题
 /**
 * This is where the invalidate() work actually happens. A full invalidate()
 * causes the drawing cache to be invalidated, but this function can be
 * called with invalidateCache set to false to skip that invalidation step
 * for cases that do not need it (for example, a component that remains at
 * the same dimensions with the same content).
 *
 * @param invalidateCache Whether the drawing cache for this view should be
 *            invalidated as well. This is usually true for a full
 *            invalidate, but may be set to false if the View's contents or
 *            dimensions have not changed.
 */
void invalidate(boolean invalidateCache) {
    //可能不同版本的api源码不太一样,这里直接看invalidateInternal方法。
    invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
}
void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,boolean fullInvalidate) {
      //我们关心的是这里 ViewParent,这个ViewPrent是一个接口,而ViewGroup与ViewRootImpl实现了它,有耐心的朋友可以在View这个类中去查找mPrent相关的一些信息,如果细心的朋友在ViewGroup类中会找到ViewRootImpl这个类在它里边的一些操作如setDragFocus等等。
        final ViewParent p = mParent;
        if (p != null && ai != null && l < r && t < b) {
            final Rect damage = ai.mTmpInvalRect;
            damage.set(l, t, r, b);
            //程序在这里检查是不是在UI线程中做操作
            p.invalidateChild(this, damage);
        }
   }
}
这个ViewRootImpl我们可能在Eclipse或者Android Studio中我们无法查看,大家可以使用Source Insight 去查看源码:打开Source Insight 打开ViewRootImpl类,找到 invalidateChild这个方法
public void invalidateChild(View child, Rect dirty) {
  //关键的地方就是这个方法
    checkThread();
  //后边的全部省略
}
 void checkThread() {
    //在这里mThread表示的是主线程,程序作了判断,检查当前线程是不是主线程,如果不是就会抛出异常
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}
看到上边方法中抛出的异常是不是感觉很熟悉,对,没错,就是我log中截出来的那句话!!那么我们现在懵逼了,为什么我们在不让子线程休眠的情况下去更新TextView文本可以,而让线程休眠两秒后就出抛异常呢?根本原因就是ViewRootImpl到底是在哪里被初始化的!ViewRootImpl是在onResume中初始化的,而我们开启的子线程是在onCreat方法中,这个时候程序没有去检测当前线程是不是主线程,所以没有抛异常!!下边我们去看ActivityThread源码,去找出原因!!
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
         if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);
            //ViewPrent实现类
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;
            if (a.mVisibleFromClient) {
                a.mWindowAdded = true;
          //问题的根源在这里,addView方法在这里对ViewRootImpl进行初始化,大家可以去看看ViewGroup的源码,找里边的addView方法,你会发现,最后又回到View的invalidate(true)方法;
                wm.addView(decor, l);
            }       
    }
}

面试会经常问到,所以整理了下留待自己使用,同时分享给大家!!有不足之处请大家留言指正,同时欢迎加入 46674429 366576264 QQ技术群,进行交流!!!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容