很多初學者肯定有這樣一個經驗,在Activity的一個子執行緒中更新UI,發現會報錯。很多人知道這個錯誤,但卻不知道是什麼原因引起的。今天我們來分析一下是什麼原因引起的。我今天以textview更新ui為例。
首先看程式碼
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.generalwei.mytest.ThreadActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="@+id/btn_change"
android:text="更換UI"/>
</RelativeLayout>複製程式碼
public class ThreadActivity extends AppCompatActivity {
private android.widget.TextView tv;
private android.widget.Button btnchange;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread);
this.btnchange = (Button) findViewById(R.id.btn_change);
this.tv = (TextView) findViewById(R.id.tv);
btnchange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
tv.setText(new Date().getTime()+"");
}
}).start();
}
});
}
}複製程式碼
執行app,點選btnchange按鈕,發現app崩潰。檢視日誌,發現這樣一個錯誤:
我們來檢視一下tv.setText()方法的原始碼。
public final void setText(CharSequence text) {
setText(text, mBufferType);
}
public void setText(CharSequence text, BufferType type) {
setText(text, type, true, 0);
if (mCharWrapper != null) {
mCharWrapper.mChars = null;
}
}
private void setText(CharSequence text, BufferType type,
boolean notifyBefore, int oldlen) {
...
if (mLayout != null) {
checkForRelayout();
}
...
}複製程式碼
這裡我們還是沒有看見什麼原因引起的,繼續追查checkForRelayout()方法。
private void checkForRelayout() {
...
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);
}複製程式碼
意思是說如果view是可見的,這個方法會重新整理view。但是必須發生在ui執行緒上。看到這邊我們發現我們的追蹤是正確。那麼接著看,為什麼一定要在ui執行緒上更新ui。
void invalidate(boolean invalidateCache) {
invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
}
void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
boolean fullInvalidate) {
...
final ViewParent p = mParent;
if (p != null && ai != null && l < r && t < b) {
final Rect damage = ai.mTmpInvalRect;
damage.set(l, t, r, b);
p.invalidateChild(this, damage);
}
...
}複製程式碼
ViewParent 是一個介面,ViewRootImpl是它的實現類,那麼我們繼續追查,程式碼如下:
@Override
public void invalidateChild(View child, Rect dirty) {
invalidateChildInParent(null, dirty);
}
@Override
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
checkThread();
...
}複製程式碼
你會發現一個檢查執行緒的方法,那麼檢視方法checkThread()。
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}複製程式碼
檢視程式碼後發現有一個mThread執行緒,它是會是UI執行緒嗎,我們就檢視Thread的來源。
public ViewRootImpl(Context context, Display display) {
...
mThread = Thread.currentThread();
...複製程式碼
發現mThread是在ViewRootImpl建立的時候賦值,這個的執行緒一定是UI執行緒。所以當前執行緒不是UI執行緒的時候會拋異常。
為什麼在onResume之前非UI執行緒也能更新UI
有時候在也能在非UI執行緒中更新,後來我們發現在onResume之前用非UI執行緒更新能UI,而onResume之後就不行了。這是因為onResume之前還沒有建立ViewRootImpl這個類,ActivityThread類中有一個handleResumeActivity方法,這個方法是用來回撥Activity的onResume方法,具體的看如下程式碼:
final void handleResumeActivity(IBinder token,boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
ActivityClientRecord r = mActivities.get(token);
if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
return;
}
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
// TODO Push resumeArgs into the activity for consideration
r = performResumeActivity(token, clearHide, reason);
if (r != null) {
if (r.window == null && !a.mFinished && willBeVisible) {
...
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (r.mPreserveWindow) {
a.mWindowAdded = true;
r.mPreserveWindow = false;
// Normally the ViewRoot sets up callbacks with the Activity
// in addView->ViewRootImpl#setView. If we are instead reusing
// the decor view we have to notify the view root that the
// callbacks may have changed.
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
if (a.mVisibleFromClient && !a.mWindowAdded) {
a.mWindowAdded = true;
wm.addView(decor, l);
}
// If the window has already been added, but during resume
// we started another activity, then don't yet make the
// window visible.
} else if (!willBeVisible) {
if (localLOGV) Slog.v(
TAG, "Launch " + r + " mStartedActivity set");
r.hideForNow = true;
}
...
// Tell the activity manager we have resumed.
if (reallyResume) {
try {
ActivityManagerNative.getDefault().activityResumed(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
} else {
// If an exception was thrown when trying to resume, then
// just end this activity.
try {
ActivityManagerNative.getDefault()
.finishActivity(token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}複製程式碼
我們可以看見這樣一個方法performResumeActivity(),它的原始碼如下:
public final ActivityClientRecord performResumeActivity(IBinder token,boolean clearHide, String reason) {
...
if (r != null && !r.activity.mFinished) {
...
r.activity.performResume();
...
}
}複製程式碼
這裡可以看見它呼叫了activity.performResume(),那麼再繼續檢視下面的原始碼:
final void performResume() {
performRestart();
...
mInstrumentation.callActivityOnResume(this);
...
onPostResume();
...
}複製程式碼
performRestart()方法主要是為了執行回撥onRestart方法,具體內容就不做分析了。mInstrumentation.callActivityOnResume()方法則是為了回撥Activity的OnResume()方法。onPostResume()方法這是為了啟用Window。
在handleResumeActivity()方法中我們可以看見一個WindowManager類,這個類是用來控制視窗顯示的,而它的addView是用來新增檢視。WindowManagerImpl是WindowManager的實現類,WindowManagerImpl的addView方法程式碼如下:
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}複製程式碼
mGlobal是WindowManagerGlobal的物件,繼續看mGlobal.addView的程式碼:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
...
ViewRootImpl root;
View panelParentView = null;
synchronized (mLock) {
// Start watching for system property changes.
if (mSystemPropertyUpdater == null) {
mSystemPropertyUpdater = new Runnable() {
@Override public void run() {
synchronized (mLock) {
for (int i = mRoots.size() - 1; i >= 0; --i) {
mRoots.get(i).loadSystemProperties();
}
}
}
};
SystemProperties.addChangeCallback(mSystemPropertyUpdater);
}
int index = findViewLocked(view, false);
if (index >= 0) {
if (mDyingViews.contains(view)) {
// Don't wait for MSG_DIE to make it's way through root's queue.
mRoots.get(index).doDie();
} else {
throw new IllegalStateException("View " + view
+ " has already been added to the window manager.");
}
// The previous removeView() had not completed executing. Now it has.
}
// If this is a panel window, then find the window it is being
// attached to for future reference.
if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
final int count = mViews.size();
for (int i = 0; i < count; i++) {
if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
panelParentView = mViews.get(i);
}
}
}
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
}
...
}複製程式碼
你可以看做ViewRootImpl的初始化是在這裡進行的,這就是為什麼在onResume之前可以更新UI了。
為什麼要這麼設計呢?
因為所有的UI控制元件都是非執行緒安全的,如果在非UI執行緒更新UI會造成UI混亂。所以一般我們會在Handler中更新UI。
如有寫的不當之處,請多指教。