View.postDelayed()/post() 原理(1)

本文深入探讨了Android中View.postDelayed()/post()的实现原理,详细分析了当View的mAttachInfo不为null时如何通过mAttachInfo.mHandler在UI线程中发送消息,以及当mAttachInfo为null时的消息处理方式。文章以Android 7.1源代码为基础,揭示了View对象与AttachInfo、Handler之间的关系,以及在View添加、布局过程中的角色。
摘要由CSDN通过智能技术生成

我们知道,Handler有postDelayed()/post()等API,在UI线程中,通过默认构造方法new Handler(),会创建一个与当前线程的Looper绑定的Handler对象,UI线程的消息循环是由框架层打开(Looper.loop()),APP开发者无需关注。维护一个挂在UI线程的Handler成员变量用以发消息/处理消息,是惯常的代码风格。
当然,还有另外一类API:View.postDelayed()/post()。Android官方文档介绍这类API也是向UI线程发消息,Runnable执行在UI线程中。与Handler.postDelayed()/post()一样,View.postDelayed()/post()的API Level是1,是非常古老的API。

1. View.postDelayed()/post()在 框架层的实现原理

本文源代码分析基于Android 7.1。从View的源代码说起:

    /**
     * <p>Causes the Runnable to be added to the message queue.
     * The runnable will be run on the user interface thread.</p>
     *
     * @param action The Runnable that will be executed.
     *
     * @return Returns true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     *
     * @see #postDelayed
     * @see #removeCallbacks
     */
    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;
    }

很清楚的两路逻辑:
(1)如果View的成员变量mAttachInfo不为null,直接post到mAttachInfo.mHandler。
(2)如果View的成员变量mAttachInfo为null,post到自身的一个runnable队列中。

1.1 post到mAttachInfo.mHandler

View的成员变量mAttachInfo对应的类是View的一个内部final类:


    /**
     * A set of information given to a view when it is attached to its parent
     * window.
     */
    final static class AttachInfo {
    ... }

在Android的框架层设计中,View需要附着在某个Window上,AttachInfo这个类显然是用于处理View的附着相关的信息。从它的构造方法可以看到关键的一些信息成员变量,其中也看到了mHandler

        /**
         * Creates a new set of attachment information with the specified
         * events handler and thread.
         *
         * @param handler the events handler the view must use
         */
        AttachInfo(IWindowSession session, IWindow window, Display display,
                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
            mSession = session;
            mWindow = window;
            mWindowToken = window.asBinder();
            mDisplay = display;
            mViewRootImpl = viewRootImpl;
            mHandler = handler;
            mRootCallbacks = effectPlayer;
        }

View的成员变量mAttachInfo在什么地方被赋值?很清晰,在View.dispatchAttachedToWindow()/dispatchDetachedFromWindow():

    /**
     * @param info the {@link android.view.View.AttachInfo} to associated with
     *        this view
     */
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio中,可以使用postDelayed方法实现延迟执行某个任务。该方法可以在指定的延迟时间后将任务添加到消息队列中,并在主线程上执行。通过使用postDelayed方法,可以实现一些简单的动画效果或在特定时间间隔内更新视图页面。 在Android Studio中,可以使用以下方法来实现延迟执行任务: 1. Activity.runOnUiThread(Runnable):可以在Activity的主线程上执行指定的任务。可以使用该方法来更新UI或执行其他需要在主线程上运行的操作。 2. View.post(Runnable):可以在一个View的主线程中执行指定的任务。可以使用该方法在特定的View上执行任务,例如更新该View的内容或执行一些与该View相关的操作。 3. View.postDelayed(Runnable, long):可以在指定的延迟时间后,在一个View的主线程中执行指定的任务。可以使用该方法来实现一些简单的动画效果或在特定时间间隔内更新视图页面。 4. Handler:可以通过Handler来实现延迟执行任务。可以使用Handler的postDelayed方法来在指定的延迟时间后执行任务。 这些方法都可以在Android Studio中使用,具体使用哪种方法取决于你的需求和应用场景。根据你提供的代码示例,你可以使用Handler的postDelayed方法来实现在指定的延迟时间后执行任务。例如,在updateThread线程的run方法中,可以使用handler.postDelayed(updateThread, 3000)来实现在3秒后再次将updateThread线程添加到线程队列中。 总结起来,Android Studio中提供了多种方法来实现延迟执行任务的功能,包括Activity.runOnUiThread、View.postView.postDelayed和Handler。选择合适的方法取决于你的需求和应用场景。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Android Studio第14课——Android当中的Handler](https://blog.csdn.net/qq997758497/article/details/80789640)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Android_Studio_Handler:Android Handler 执行绪教学](https://download.csdn.net/download/weixin_42128558/18311268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Android Studio App开发实战项目之计时器(附源码 简单易懂,适合新手学习)](https://blog.csdn.net/jiebaoshayebuhui/article/details/127812715)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值