【从BUG说起】View.post/remove runnable失败引起的BUG

982 阅读3分钟

问题:为什么runnable还会执行?不是已经被remove了吗?

前些天,同事求助说:为什么runnable还会执行?不是已经被remove了吗? 收到求助,第一时间反应:View post/remove runnable使用不当? 看了相关调用代码,证实了我的想法:

//XXXFragment.kt
override fun onDestroyView() {
    super.onDestroyView()
    ……
    binding.recyclerView.removeCallbacks(delayRunnable)
    ……
}
//delayRunnable是在其他时机View.postDelay:
binding.recyclerView.postDelay(delayRunnable,200)

同事只是遇到remove失败的问题,但是对于View post/remove runnable,不少新人容易犯下错误:

post为什么不执行?? remove为什么失败??

要了解这两个问题,我们得从源码来分析。

1. View.post(Runnable)为什么不执行?

先看View.post(Runnable)的实现:

//View.java
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;
}

可以看到:

  • 如果 mAttachInfo 非null(attached), Runnable 交由mAttachInfo内部的 Handler 进行post
  • 如果 mAttachInfo 为null(not attached), Runnable 交由 HandlerActionQueue(getRunQueue) 进行post
1.1attachInfo与attachInfo.handler的值

addView -> attachToWindow是,对mAttachInfo赋值

//View.java
void dispatchAttachedToWindow(AttachInfo info, int visibility) { 
    ……
    mAttachInfo = info; 
    ……
}

而attachInfo是在ViewRootImpl创建时创建的:

//ViewRootImpl.java
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);
     ……
}

同时可以看到:attachInfo.handler就是ViewRootHandler,而ViewRootHandler绑定的是MainLooper,是MainHandler.

所以:当view attachedWindow后,view.post实质放到MainLooper的队列里

1.2 HandlerActionQueue简单分析

//HandlerActionQueue.java
public class HandlerActionQueue {
    ……
    private HandlerAction[] mActions;
 
    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 removeCallbacks(Runnable action) {
        synchronized (this) {
            final int count = mCount;
            int j = 0;
            final HandlerAction[] actions = mActions;
            for (int i = 0; i < count; i++) {
                if (actions[i].matches(action)) {
                    // Remove this action by overwriting it within
                    // this loop or nulling it out later.
                    continue;
                }
                if (j != i) {
                    // At least one previous entry was removed, so
                    // this one needs to move to the "new" list.
                    actions[j] = actions[i];
                }
                j++;
            }
            // The "new" list only has j entries.
            mCount = j;
            // Null out any remaining entries.
            for (; j < count; j++) {
                actions[j] = null;
            }
        }
    }

    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;
        }
    }
    ……
}

getRunQueue().post(action)只是将 Runnable 对象保存到了 mActions 数组中,在 attchWindow时,调用executeActions方法来执行Runnable方法:

//View.java
void dispatchAttachedToWindow(AttachInfo info, int visibility) { 
    ……
    // Transfer all pending runnables. 
    if (mRunQueue != null) {
        mRunQueue.executeActions(info.mHandler); 
        mRunQueue = null; 
    } 
    ……
}

1.3 View.post兼容问题

由于View.post的实现在SDK<24的实现是不同的,所以在SDK<24表现也不同。

View.java
//SDK >= 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; 
} 

//SDK < 24
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;
}

在 SDK <=23,当 attachInfo 为 null 时, Runnable 保存到 ViewRootImpl 内部的一个静态成员变量 sRunQueues 中。而 sRunQueues 内部是通过 ThreadLocal 来保存 RunQueue 的,这意味着不同线程获取到的 RunQueue 是不同对象。

//ViewRootImpl.java
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; 
 }

如果在子线程使用View.post(Runnable),该Runnable永远不会被执行,因为主线程根本无法获取到子线程的 RunQueue

1.4 View.post(Runnable)不执行原因

由上面的源码,我们可以看到:

  • SDK >= 24
  1. View一直没有attachWindow,那么View.post Runnable一直不执行。
  2. View已经attachWindowpost runnable,相当于MainHandler post,均被执行
  3. View没有attachWindowpost runnable,在attachWindow时执行
  • SDK<24
  1. 当在主线程View.post Runnable,不管View attachWindow与否,Runnable都会被执行
  2. 当在子线程View.post Runnable,如果View attachWindowRunnable正常被执行。如果View not attachWindow,Runnable永远不会被执行

2 View.remove runnable为什么失败

2.1 先看看View.remove runnable的实现

//View.java
//SDK >=24
public boolean removeCallbacks(Runnable action) {
    if (action != null) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            attachInfo.mHandler.removeCallbacks(action);
            attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
                    Choreographer.CALLBACK_ANIMATION, action, null);
        }
        getRunQueue().removeCallbacks(action);
    }
    return true;
}
//SDK < 24
public boolean removeCallbacks(Runnable action) {
   if (action != null) {
       final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
           attachInfo.mHandler.removeCallbacks(action);
           attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
                    Choreographer.CALLBACK_ANIMATION, action, null);
        } else {
            // Assume that post will succeed later
            ViewRootImpl.getRunQueue().removeCallbacks(action);
        }
    }
    return true;
}

可以看到:

  1. 对于 SDK >= 24
  •  mAttachInfo 非null(attached),由mAttachInfo内部的 Handler进行remove runnable
  • 不管attached/dettached,HandlerActionQueue(getRunQueue) 都进行remove runnable
  1. 对于 SDK < 24
  • 如果 mAttachInfo 非null(attached),由mAttachInfo内部的 Handler进行remove runnable
  • mAttachInfo 为null(not attached), 获取ViewRootImpl 内部的一个静态成员变量 ThreadLocal sRunQueues 进行remove。

2.2 View.remove runnable失败原因

根本原因是:post处理对象与remove处理对象不同

  • 进行post时,view的状态(attached/dettached)与进行remove时的不同
  • 例如:post时,view attached,此时交由MainLooper处理。但remove时,view已经dettached,此时由HandlerActionQueue进行remove。post与remove的实质操作对象并不是同一个对象,那remove肯定失败

3 项目Fragment.onDestroy->view.remove runnable 失败分析

由上面的分析,我们很快知道:

//XXXFragment.kt
override fun onDestroyView() {
    super.onDestroyView()
    ……
    binding.recyclerView.removeCallbacks(delayRunnable)
    ……
}
//delayRunnable是在其他时机View.postDelay:
binding.recyclerView.postDelay(delayRunnable,200)

post/remove操作时View的attached/dettached状态不同。 由项目代码可以清楚看到,View.post runnable时,确实是在View.attached状态的。 但View.remove runnable是在Fragment.onDestroyView里进行的。 去看看Fragment.onDestroyView前发生了什么:

//FragmentStateManager.java
void destroyFragmentView() {
    ……
    if (mFragment.mContainer != null && mFragment.mView != null) {
        mFragment.mContainer.removeView(mFragment.mView);
    }
    mFragment.performDestroyView();
    mDispatcher.dispatchOnFragmentViewDestroyed(mFragment, false);
    ……
}
//Fragment.java
void performDestroyView() {
    mChildFragmentManager.dispatchDestroyView();
    if (mView != null) {
        mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
    }
    mState = CREATED;
    mCalled = false;
    onDestroyView();
    if (!mCalled) {
        throw new SuperNotCalledException("Fragment " + this
                + " did not call through to super.onDestroyView()");
    }
    // Handles the detach/reattach case where the view hierarchy
    // is destroyed and recreated and an additional call to
    // onLoadFinished may be needed to ensure the new view
    // hierarchy is populated from data from the Loaders
    LoaderManager.getInstance(this).markForRedelivery();
    mPerformedCreateView = false;
}

调用栈: FragmentStateManaget. destroyFragmentView->Fragment.removeView->Fragment. performDestroyView->Fragment.onDestroyView

  • 可见:在Fragment.onDestroyView时,fragment.view早已经被remove,即view dettached

结合上面的分析,容易知道为什么项目代码view remove runnable失败的原因了

4 总结

在使用View post/remove runnable时,需要特别注意View的attached/dettached状态。同时对于view.post时,可能会不被执行的场景,需要了解掌握的。