Android View.Post 的原理及缺陷

很多开发者都了解这么一个知识点:在 Activity 的 onCreate 方法里我们无法直接获取到 View 的宽高信息,但通过 View.post(Runnable)这种方式就可以,那背后的具体原因你是否有了解过呢?

读者可以尝试以下操作。可以发现,除了通过 View.post(Runnable)这种方式可以获得 View 的真实宽高外,其它方式取得的值都是 0

/**
 * 作者:leavesC
 * 时间:2020/03/14 11:05
 * 描述:
 * GitHub:https://github.com/leavesC
 */
class MainActivity : AppCompatActivity() {

 private val view by lazy {
  findViewById<View>(R.id.view)
 }

 override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
  getWidthHeight("onCreate")
  view.post {
   getWidthHeight("view.Post")
  }
  Handler().post {
   getWidthHeight("handler")
  }
 }

 override fun onResume() {
  super.onResume()
  getWidthHeight("onResume")
 }

 private fun getWidthHeight(tag: String) {
  Log.e(tag, "width: " + view.width)
  Log.e(tag, "height: " + view.height)
 }

}
github.leavesc.view E/onCreate: width: 0
github.leavesc.view E/onCreate: height: 0
github.leavesc.view E/onResume: width: 0
github.leavesc.view E/onResume: height: 0
github.leavesc.view E/handler: width: 0
github.leavesc.view E/handler: height: 0
github.leavesc.view E/view.Post: width: 263
github.leavesc.view E/view.Post: height: 263

从这就可以引申出几个疑问:

  • View.post(Runnable) 为什么可以得到 View 的真实宽高
  • Handler.post(Runnable)View.post(Runnable)有什么区别
  • onCreateonResume 函数中为什么无法直接得到 View 的真实宽高
  • View.post(Runnable) 中的 Runnable 是由谁来执行的,可以保证一定会被执行吗

后边就来一一解答这几个疑问,本文基于 Android API 30 进行分析

一、View.post(Runnable)

看下 View.post(Runnable) 的方法签名,可以看出 Runnable 的处理逻辑分为两种:

  • 如果 mAttachInfo 不为 null,则将 Runnable 交由mAttachInfo内部的 Handler 进行处理
  • 如果 mAttachInfo 为 null,则将 Runnable 交由 HandlerActionQueue 进行处理
 public boolean post(Runnable action) {
  final AttachInfo attachInfo = mAttachInfo;
  if (attachInfo != null) {
   return attachInfo.mHandler.post(action);
  }
  // Postpone the runnable until we know on which thread it needs to run.
  // Assume that the runnable will be successfully placed after attach.
  getRunQueue().post(action);
  return true;
 }

 private HandlerActionQueue getRunQueue() {
  if (mRunQueue == null) {
   mRunQueue = new HandlerActionQueue();
  }
  return mRunQueue;
 }

1、AttachInfo

先来看View.post(Runnable)的第一种处理逻辑

AttachInfo 是 View 内部的一个静态类,其内部持有一个 Handler 对象,从注释可知它是由 ViewRootImpl 提供的

final static class AttachInfo {

  /**
   * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
   * handler can be used to pump events in the UI events queue.
   */
  @UnsupportedAppUsage
  final Handler mHandler;

 	AttachInfo(IWindowSession session, IWindow window, Display display,
    ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer,
    Context context) {
   ···
   mHandler = handler;
   ···
 	}

 	···
}

查找 mAttachInfo 的赋值时机可以追踪到 View 的 dispatchAttachedToWindow 方法,该方法被调用就意味着 View 已经 Attach 到 Window 上了

	@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
  mAttachInfo = info;
  ···
 }

再查找dispatchAttachedToWindow 方法的调用时机,可以跟踪到 ViewRootImpl 类。ViewRootImpl 内就包含一个 Handler 对象 mHandler,并在构造函数中以 mHandler 作为构造参数之一来初始化 mAttachInfo。ViewRootImpl 的performTraversals()方法就会调用 DecorView 的 dispatchAttachedToWindow 方法并传入 mAttachInfo,从而层层调用整个视图树中所有 View 的 dispatchAttachedToWindow 方法,使得所有 childView 都能获取到 mAttachInfo 对象

	final ViewRootHandler mHandler = new ViewRootHandler();

 public ViewRootImpl(Context context, Display display, IWindowSession session,
      boolean useSfChoreographer) {
  ···
  mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this,
    context);
  ···
 }

 private void performTraversals() {
  ···
  if (mFirst) {
   ···
   host.dispatchAttachedToWindow(mAttachInfo, 0);
 	 ···
  }
  ···
  performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
  performLayout(lp, mWidth, mHeight);
  performDraw();
  ···
 }

此外,performTraversals()方法也负责启动整个视图树的 Measure、Layout、Draw 流程,只有当 performLayout 被调用后 View 才能确定自己的宽高信息。而 performTraversals()本身也是交由 ViewRootHandler 来调用的,即整个视图树的绘制任务也是先插入到 MessageQueue 中,后续再由主线程取出任务进行执行。由于插入到 MessageQueue 中的消息是交由主线程来顺序执行的,所以 attachInfo.mHandler.post(action)就保证了 action 一定是在 performTraversals 执行完毕后才会被调用,因此我们就可以在 Runnable 中获取到 View 的真实宽高了

2、HandlerActionQueue

再来看View.post(Runnable)的第二种处理逻辑

HandlerActionQueue 可以看做是一个专门用于存储 Runnable 的任务队列,mActions 就存储了所有要执行的 Runnable 和相应的延时时间。两个post方法就用于将要执行的 Runnable 对象保存到 mActions中,executeActions就负责将mActions中的所有任务提交给 Handler 执行

public class HandlerActionQueue {

 private HandlerAction[] mActions;
 private int mCount;

 public void post(Runnable action) {
  postDelayed(action, 0);
 }

 public void postDelayed(Runnable action, long delayMillis) {
  final HandlerAction handlerAction = new HandlerAction(action, delayMillis);
  synchronized (this) {
   if (mActions == null) {
    mActions = new HandlerAction[4];
   }
   mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
   mCount++;
  }
 }

 public void executeActions(Handler handler) {
  synchronized (this) {
   final HandlerAction[] actions = mActions;
   for (int i = 0, count = mCount; i < count; i++) {
    final HandlerAction handlerAction = actions[i];
    handler.postDelayed(handlerAction.action, handlerAction.delay);
   }

   mActions = null;
   mCount = 0;
  }
 }

 private static class HandlerAction {
  final Runnable action;
  final long delay;

  public HandlerAction(Runnable action, long delay) {
   this.action = action;
   this.delay = delay;
  }

  public boolean matches(Runnable otherAction) {
   return otherAction == null && action == null
     || action != null && action.equals(otherAction);
  }
 }

 ···

}

所以说,getRunQueue().post(action)只是将我们提交的 Runnable 对象保存到了 mActions 中,还需要外部主动调用 executeActions方法来执行任务

而这个主动执行任务的操作也是由 View 的 dispatchAttachedToWindow来完成的,从而使得 mActions 中的所有任务都会被插入到 mHandler 的 MessageQueue 中,等到主线程执行完 performTraversals() 方法后就会来执行 mActions,所以此时我们依然可以获取到 View 的真实宽高

	@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
  mAttachInfo = info;
  ···
  // Transfer all pending runnables.
  if (mRunQueue != null) {
   mRunQueue.executeActions(info.mHandler);
   mRunQueue = null;
  }
  ···
 }

二、Handler.post(Runnable)

Handler.post(Runnable)View.post(Runnable)有什么区别呢?

从上面的源码分析就可以知道,View.post(Runnable)之所以可以获取到 View 的真实宽高,主要就是因为确保了获取 View 宽高的操作一定是在 View 绘制完毕之后才被执行,而 Handler.post(Runnable)之所以不行,就是其无法保证这一点

虽然这两种post(Runnable)的操作都是往同个 MessageQueue 插入任务,且最终都是交由主线程来执行。但绘制视图树的任务是在onResume被回调后才被提交的,所以我们在onCreate中用 Handler 提交的任务就会早于绘制视图树的任务被执行,因此也就无法获取到 View 的真实宽高了

三、onCreate & onResume

onCreateonResume 函数中为什么无法也直接得到 View 的真实宽高呢?

从结果反推原因,这说明当 onCreate、onResume被回调时 ViewRootImpl 的 performTraversals()方法还未执行,那么performTraversals()方法的具体执行时机是什么时候呢?

这可以从 ActivityThread -> WindowManagerImpl -> WindowManagerGlobal -> ViewRootImpl 这条调用链上找到答案

首先,ActivityThread 的 handleResumeActivity 方法就负责来回调 Activity 的 onResume 方法,且如果当前 Activity 是第一次启动,则会向 ViewManager(wm)添加 DecorView

	@Override
 public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
   String reason) {
  ···
  //Activity 的 onResume 方法
  final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
  ···
  if (r.window == null && !a.mFinished && willBeVisible) {
   ···
   ViewManager wm = a.getWindowManager();
   if (a.mVisibleFromClient) {
    if (!a.mWindowAdded) {
     a.mWindowAdded = true;
     //重点
     wm.addView(decor, l);
    } else {
     a.onWindowAttributesChanged(l);
    }
   }
  } else if (!willBeVisible) {
   if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
   r.hideForNow = true;
  }
		···
 }

此处的 ViewManager 的具体实现类即 WindowManagerImpl,WindowManagerImpl 会将操作转交给 WindowManagerGlobal

 @UnsupportedAppUsage
 private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();

	@Override
 public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
  applyDefaultToken(params);
  mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
    mContext.getUserId());
 }

WindowManagerGlobal 就会完成 ViewRootImpl 的初始化并且调用其 setView 方法,该方法内部就会再去调用 performTraversals 方法启动视图树的绘制流程

public void addView(View view, ViewGroup.LayoutParams params,
   Display display, Window parentWindow, int userId) {
  ···
  ViewRootImpl root;
  View panelParentView = null;
  synchronized (mLock) {
   ···
   root = new ViewRootImpl(view.getContext(), display);
   view.setLayoutParams(wparams);
   mViews.add(view);
   mRoots.add(root);
   mParams.add(wparams);
   // do this last because it fires off messages to start doing things
   try {
    root.setView(view, wparams, panelParentView, userId);
   } catch (RuntimeException e) {
    // BadTokenException or InvalidDisplayException, clean up.
    if (index >= 0) {
     removeViewLocked(index, true);
    }
    throw e;
   }
  }
 }

所以说, performTraversals 方法的调用时机是在 onResume 方法之后,所以我们在 onCreateonResume 函数中都无法获取到 View 的实际宽高。当然,当 Activity 在单次生命周期过程中第二次调用onResume 方法时自然就可以获取到 View 的宽高属性

四、View.post(Runnable) 的兼容性

从以上分析可以得出一个结论:由于 View.post(Runnable)最终都是往和主线程关联的 MessageQueue 中插入任务且最终由主线程来顺序执行,所以即使我们是在子线程中调用View.post(Runnable),最终也可以得到 View 正确的宽高值

但该结论也只在 API 24 及之后的版本上才成立,View.post(Runnable) 方法也存在着一个版本兼容性问题,在 API 23 及之前的版本上有着不同的实现方式

	//Android API 24 及之后的版本
	public boolean post(Runnable action) {
  final AttachInfo attachInfo = mAttachInfo;
  if (attachInfo != null) {
   return attachInfo.mHandler.post(action);
  }
  // Postpone the runnable until we know on which thread it needs to run.
  // Assume that the runnable will be successfully placed after attach.
  getRunQueue().post(action);
  return true;
 }

	//Android API 23 及之前的版本
	public boolean post(Runnable action) {
  final AttachInfo attachInfo = mAttachInfo;
  if (attachInfo != null) {
   return attachInfo.mHandler.post(action);
  }
  // Assume that post will succeed later
  ViewRootImpl.getRunQueue().post(action);
  return true;
 }

在 Android API 23 及之前的版本上,当 attachInfo 为 null 时,会将 Runnable 保存到 ViewRootImpl 内部的一个静态成员变量 sRunQueues 中。而 sRunQueues 内部是通过 ThreadLocal 来保存 RunQueue 的,这意味着不同线程获取到的 RunQueue 是不同对象,这也意味着如果我们在子线程中调用View.post(Runnable) 方法的话,该 Runnable 永远不会被执行,因为主线程根本无法获取到子线程的 RunQueue

 static final ThreadLocal<RunQueue> sRunQueues = new ThreadLocal<RunQueue>();

	static RunQueue getRunQueue() {
  RunQueue rq = sRunQueues.get();
  if (rq != null) {
   return rq;
  }
  rq = new RunQueue();
  sRunQueues.set(rq);
  return rq;
 }

此外,由于sRunQueues 是静态成员变量,主线程会一直对应同一个 RunQueue 对象,如果我们是在主线程中调用View.post(Runnable)方法的话,那么该 Runnable 就会被添加到和主线程关联的 RunQueue 中,后续主线程就会取出该 Runnable 来执行

即使该 View 是我们直接 new 出来的对象(就像以下的示例),以上结论依然生效,当系统需要绘制其它视图的时候就会顺便取出该任务,一般很快就会执行到。当然,由于此时 View 并没有 AttachedToWindow,所以获取到的宽高值肯定也是 0

  val view = View(Context)
  view.post {
   getWidthHeight("view.Post")
  }

View.post(Runnable)方法的兼容性问题做下总结:

  • 当 API < 24 时,如果是在主线程进行调用,那么不管 View 是否有 AttachedToWindow,提交的 Runnable 均会被执行。但只有在 View 被 AttachedToWindow 的情况下才可以获取到 View 的真实宽高
  • 当 API < 24 时,如果是在子线程进行调用,那么不管 View 是否有 AttachedToWindow,提交的 Runnable 都将永远不会被执行
  • 当 API >= 24 时,不管是在主线程还是子线程进行调用,只要 View 被 AttachedToWindow 后,提交的 Runnable 都会被执行,且都可以获取到 View 的真实宽高值。如果没有被 AttachedToWindow 的话,Runnable 也将永远不会被执行

以上就是Android View.Post 的原理及缺陷的详细内容,更多关于Android View.Post的资料请关注我们其它相关文章!

(0)

相关推荐

  • Android自定义View实现分段选择按钮的实现代码

    首先演示下效果,分段选择按钮,支持点击和滑动切换. 视图绘制过程中,要执行onMeasure.onLayout.onDraw等方法,这也是自定义控件最常用到的几个方法. onMeasure:测量视图的大小,可以根据MeasureSpec的Mode确定父视图和子视图的大小. onLayout:确定视图的位置 onDraw:绘制视图 这里就不做过多的介绍,主要介绍本控件涉及的到的部分. 1.1 获取item大小.起始位置 @Override protected void onMeasure(int

  • Android自定义view之太极图的实现教程

    太极图 周四课余时间比较多,正好前几天为了给小学弟解决问题,回顾了一些Android的知识,(上学还是不能把以前上班学到的东西丢掉)于是写一篇关于自定义view的文章. 最后完成的样子(可旋转) 这篇文章主要内容为使用Canvas画简单图案,自定义属性,以及属性动画ObjectAnimator中的旋转动画 提示:以下是本篇文章正文内容 一.先画一个太极 先介绍一下定义的东西: private int useWidth; //最后测量得到的值 private int leftcolor; //左太

  • Android使用setContentView实现页面的转换效果

    一提到Android中页面的切换,你是不是只想到了startActivity启动另一个Activity? 其实在Android中,可以直接利用setContentView达到类似页面转换效果的!实现思路如下: 在第一个Activity的布局中添加一个Button,实现点击事件 点击该Button,调用setContentView,传入第二个页面的Layout,第二个页面就显示出来了 第二个页面的布局中仍然有一个Button,仍然实现其点击事件 点击该Button,调用setContentView

  • Android自定义View仿大众点评星星评分控件

    本文实例为大家分享了Android仿大众点评星星评分控件的具体代码,供大家参考,具体内容如下 话不多说,直接上代码,这里采用的是自定View public class RatingBar extends View { // 正常.半个和选中的星星 private Bitmap mStarNormal, mStarHalf, mStarSelected; //星星的总数 private int mStartTotalNumber = 5; //选中的星星个数 private float mSele

  • Android自定义view之围棋动画效果的实现

    前言 废话不多说直接开始 老规矩,文章最后有源码 完成效果图 棋子加渐变色 棋子不加渐变色 一.测量 1.获取宽高 @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; useWidth = mWidth; if (mWidth > mHeight) { useWidth =

  • Android 中 WebView 的基本用法详解

    加载 URL (网络或者本地 assets 文件夹下的 html 文件) 加载 html 代码 Native 和 JavaScript 相互调用 加载网络 URL webview.loadUrl(https://www.baidu.com/); 加载 assets 下的 html 文件 webview.loadUrl(file:///android_asset/test.html); 加载 html 代码 // 两个代码差不多 // 偶尔出现乱码 webview.loadData(); // 比

  • Android 滑动Scrollview标题栏渐变效果(仿京东toolbar)

    Scrollview标题栏滑动渐变 仿京东样式(上滑显示下滑渐变消失) /** * @ClassName MyScrollView * @Author Rex * @Date 2021/1/27 17:38 */ public class MyScrollView extends ScrollView { private TranslucentListener mTranslucentListener; public void setTranslucentListener(Translucent

  • Android使用TypeFace设置TextView的文字字体

    在Android里面设置一个TextView的文字颜色和文字大小,都很简单,也是一个常用的基本功能.但很少有设置文字字体的,今天要分享的是通过TypeFace去设置TextView的文字字体,布局里面有两个Button,总共包含两个小功能:换字体和变大. 功能的核心部分主要是两点: 创建assets外部资源文件夹,将ttf格式的字体文件放在该目录下 通过TypeFace类的createFromAsset方法,让TextView通过setTypeFace来改变字体 完整源码如下: 1.主Activ

  • 源码详解Android中View.post()用法

    emmm,大伙都知道,子线程是不能进行 UI 操作的,或者很多场景下,一些操作需要延迟执行,这些都可以通过 Handler 来解决.但说实话,实在是太懒了,总感觉写 Handler 太麻烦了,一不小心又很容易写出内存泄漏的代码来,所以为了偷懒,我就经常用 View.post() or View.postDelay() 来代替 Handler 使用. 但用多了,总有点心虚,View.post() 会不会有什么隐藏的问题?所以趁有点空余时间,这段时间就来梳理一下,View.post() 原理到底是什

  • Android使用ScrollView实现滚动效果

    本文实例为大家分享了ScrollView实现滚动效果的具体代码,供大家参考,具体内容如下 如果长文本的内容超过一屏幕 则只能显示一屏幕的内容 设置ScrollView 通过滚动浏览下面的内容 若将标签更改为<HorizontalScrollView></HorizontalScrollView>则为水平滚动效果 xml文件: <?xml version="1.0" encoding="utf-8"?> <android.su

随机推荐