a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 系統 > Android > 正文

Android子線程與更新UI問題的深入講解

2019-10-21 21:31:02
字體:
來源:轉載
供稿:網友

前言

在Android項目中經常有碰到這樣的問題,在子線程中完成耗時操作之后要更新UI,下面就自己經歷的一些項目總結一下更新的方法。話不多說了,來一起看看詳細的介紹吧

引子:

情形1

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.home_tv); ImageView imageView = findViewById(R.id.home_img); new Thread(new Runnable() {  @Override  public void run() {  textView.setText("更新TextView");  imageView.setImageResource(R.drawable.img);  } }).start(); }

運行結果:正常運行!!!

情形二

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.home_tv); ImageView imageView = findViewById(R.id.home_img); new Thread(new Runnable() {  @Override  public void run() {  try {   Thread.sleep(5000);  } catch (InterruptedException e) {   e.printStackTrace();  }  textView.setText("更新TextView");  imageView.setImageResource(R.drawable.img);  } }).start(); }

運行結果:異常

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:874)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
        at android.view.View.requestLayout(View.java:17476)
        at android.widget.TextView.checkForRelayout(TextView.java:6871)
        at android.widget.TextView.setText(TextView.java:4057)
        at android.widget.TextView.setText(TextView.java:3915)
        at android.widget.TextView.setText(TextView.java:3890)
        at com.dong.demo.MainActivity$1.run(MainActivity.java:44)
        at java.lang.Thread.run(Thread.java:818)

不是說,子線程不能更新UI嗎,為什么情形一可以正常運行,情形二不能正常運行呢;

子線程修改UI出現異常,與什么方法有關

首先從出現異常的log日志入手,發現出現異常的方法調用順序如下:

TextView.setText(TextView.java:4057)

TextView.checkForRelayout(TextView.java:6871)

View.requestLayout(View.java:17476)

RelativeLayout.requestLayout(RelativeLayout.java:360)

View.requestLayout(View.java:17476)

ViewRootImpl.requestLayout(ViewRootImpl.java:874)

ViewRootImpl.checkThread(ViewRootImpl.java:6357)

更改ImageView時,出現的異常類似;

首先看TextView.setText()方法的源碼

 private void setText(CharSequence text, BufferType type,    boolean notifyBefore, int oldlen) {  //省略其他代碼 if (mLayout != null) {  checkForRelayout(); } sendOnTextChanged(text, 0, oldlen, textLength); onTextChanged(text, 0, oldlen, textLength); //省略其他代碼

然后,查看以下checkForRelayout()方法的與源碼。

 private void checkForRelayout() { // If we have a fixed width, we can just swap in a new text layout // if the text height stays the same or if the view height is fixed. if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT  //省略代碼  // We lose: the height has changed and we have a dynamic height.  // Request a new view layout using our new text layout.  requestLayout();  invalidate(); } else {  // Dynamic width, so we have no choice but to request a new  // view layout with a new text layout.  nullLayouts();  requestLayout();  invalidate(); } }

checkForReLayout方法,首先會調用需要改變的View的requestLayout方法,然后執行invalidate()重繪操作;

TextView沒有重寫requestLayout方法,requestLayout方法由View實現;

查看RequestLayout方法的源碼:

 public void requestLayout() { //省略其他代碼 if (mParent != null && !mParent.isLayoutRequested()) {  mParent.requestLayout(); } if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {  mAttachInfo.mViewRequestingLayout = null; } }

View獲取到父View(類型是ViewParent,ViewPaerent是個接口,requestLayout由子類來具體實現),mParent,然后調用父View的requestLayout方法,比如示例中的父View就是xml文件的根布局就是RelativeLayout。

 @Override public void requestLayout() { super.requestLayout(); mDirtyHierarchy = true; }

繼續跟蹤super.requestLayout()方法,即ViewGroup沒有重新,即調用的是View的requestLayout方法。

經過一系列的調用ViewParent的requestLayout方法,最終調用到ViewRootImp的requestLayout方法。ViewRootImp實現了ViewParent接口,繼續查看ViewRootImp的requestLayout方法源碼。

 @Override public void requestLayout() {  if (!mHandlingLayoutInLayoutRequest) {   checkThread();   mLayoutRequested = true;   scheduleTraversals();  } }

ViewRootImp的requestLayout方法中有兩個方法:

一、checkThread,檢查線程,源碼如下

 void checkThread() {  if (mThread != Thread.currentThread()) {   throw new CalledFromWrongThreadException(     "Only the original thread that created a view hierarchy can touch its views.");  } }

判斷當前線程,是否是創建ViewRootImp的線程,而創建ViewRootImp的線程就是主線程,當前線程不是主線程的時候,就拋出異常。

二、scheduleTraversals(),查看源碼:

 void scheduleTraversals() {  if (!mTraversalScheduled) {   mTraversalScheduled = true;   mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();   mChoreographer.postCallback(     Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);   if (!mUnbufferedInputDispatch) {    scheduleConsumeBatchedInput();   }   notifyRendererOfFramePending();   pokeDrawLockIfNeeded();  } }

查看mTraversalRunnable中run()方法的具體操作

 final class TraversalRunnable implements Runnable {  @Override  public void run() {   doTraversal();  } }

繼續追蹤doTraversal()方法

 void doTraversal() {  if (mTraversalScheduled) {   mTraversalScheduled = false;   mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);   if (mProfile) {    Debug.startMethodTracing("ViewAncestor");   }   performTraversals();   if (mProfile) {    Debug.stopMethodTracing();    mProfile = false;   }  } }

查看到performTraversals()方法,熟悉了吧,這是View繪制的起點。

Android,子線程,更新UI

總結一下:

1.Android更新UI會調用View的requestLayout()方法,在requestLayout方法中,獲取ViewParent,然后調用ViewParent的requestLayout()方法,一直調用下去,直到調用到ViewRootImp的requestLayout方法;

2.ViewRootImp的requetLayout方法,主要有兩部操作一個是checkThread()方法,檢測線程,一個是scheduleTraversals,執行繪制相關工作;

情形3

 @Override protected void onCreate(Bundle savedInstanceState) {  Log.i("Dong", "Activity: onCreate");  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  new Thread(new Runnable() {   @Override   public void run() {    Looper.prepare();    try {     Thread.sleep(5000);    } catch (InterruptedException e) {     e.printStackTrace();    }    Toast.makeText(MainActivity.this, "顯示Toast", Toast.LENGTH_LONG).show();    Looper.loop();   }  }).start(); }

運行結果:正常

分析

下面從Toast源碼進行分析:

 public static Toast makeText(Context context, CharSequence text, @Duration int duration) {  return makeText(context, null, text, duration); }

makeText方法調用了他的重載方法,繼續追蹤

 public static Toast makeText(@NonNull Context context, @Nullable Looper looper,   @NonNull CharSequence text, @Duration int duration) {  Toast result = new Toast(context, looper);  LayoutInflater inflate = (LayoutInflater)    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);  TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);  tv.setText(text);  result.mNextView = v;  result.mDuration = duration;  return result; }

新建了一個Toast對象,然后對顯示的布局、內容、時長進行了設置,并返回Toast對象。

繼續查看new Toast()的源碼

 public Toast(@NonNull Context context, @Nullable Looper looper) {  mContext = context;  mTN = new TN(context.getPackageName(), looper);  mTN.mY = context.getResources().getDimensionPixelSize(    com.android.internal.R.dimen.toast_y_offset);  mTN.mGravity = context.getResources().getInteger(    com.android.internal.R.integer.config_toastDefaultGravity); }

繼續查看核心代碼 mTN = new TN(context.getPackageName(), looper);

TN初始化的源碼為:

  TN(String packageName, @Nullable Looper looper) {   //省略部分不相關代碼   if (looper == null) {    // 沒有傳入Looper對象的話,使用當前線程對應的Looper對象    looper = Looper.myLooper();    if (looper == null) {     throw new RuntimeException(       "Can't toast on a thread that has not called Looper.prepare()");    }   }   //初始化了Handler對象   mHandler = new Handler(looper, null) {    @Override    public void handleMessage(Message msg) {     switch (msg.what) {      case SHOW: {       IBinder token = (IBinder) msg.obj;       handleShow(token);       break;      }      case HIDE: {       handleHide();       // Don't do this in handleHide() because it is also invoked by       // handleShow()       mNextView = null;       break;      }      case CANCEL: {       handleHide();       // Don't do this in handleHide() because it is also invoked by       // handleShow()       mNextView = null;       try {        getService().cancelToast(mPackageName, TN.this);       } catch (RemoteException e) {       }       break;      }     }    }   };  }

繼續追蹤handleShow(token)方法:

  public void handleShow(IBinder windowToken) {   //省略部分代碼   if (mView != mNextView) {    // remove the old view if necessary    handleHide();    mView = mNextView;    Context context = mView.getContext().getApplicationContext();    String packageName = mView.getContext().getOpPackageName();    if (context == null) {     context = mView.getContext();    }    mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);    /*    ·*省略設置顯示屬性的代碼    ·*/    if (mView.getParent() != null) {     if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);     mWM.removeView(mView);    }=    try {     mWM.addView(mView, mParams);     trySendAccessibilityEvent();    } catch (WindowManager.BadTokenException e) {     /* ignore */    }   }  }

通過源碼可以看出,Toast顯示內容是通過mWM(WindowManager類型)的直接添加的,更正:mWm.addView 時,對應的ViewRootImp初始化發生在子線程,checkThread方法中的mThread != Thread.currentThread()判斷為true,所以不會拋出只能在主線程更新UI的異常。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 九九精品久久 | 国产成人在线免费观看 | 四虎在线看片 | 精品免费在线 | 极品少妇一区二区三区精品视频 | 国产精品国产三级国产aⅴ原创 | 超碰香蕉 | 毛片av网站| 激情视频网站 | 亚洲福利国产 | 中文字幕一区二区三区精彩视频 | 中文在线一区 | 免费高潮视频95在线观看网站 | 日本免费一区二区三区 | 亚洲精品不卡 | 黄色在线免费看 | 亚洲欧美一区二区精品中文字幕 | 在线看av的网址 | 精品久久久久香蕉网 | 91精品国产91久久久久久久久久久久 | 激情五月婷婷 | 国产精品久久久久久久蜜臀 | 亚洲精品成人在线 | 国产精品欧美日韩在线观看 | 久久国产精品亚州精品毛片 | 久草视频在线资源 | 毛片免费看 | 欧美日韩高清在线一区 | 欧美日韩在线精品 | 日韩1区| 欧美久久久久久 | 99久久99久久精品国产片果冻 | 九九热这里只有精 | 九色视频在线播放 | 欧美成人精品一区二区男人看 | 久久夜夜操 | 欧美成人一区二区三区片免费 | 国产丝袜一区二区三区免费视频 | 黄色毛片观看 | 亚洲精品中文字幕乱码无线 | 在线超碰 |