Handler简单分析-runOnUiThread,view.post()

这篇博客主要分析了Handler在Android应用中的使用,特别是runOnUiThread和View.post()方法。这两个方法都确保代码在UI线程执行,通过查看源码,揭示了它们最终如何通过Handler的sendMessageAtTime方法将任务放入MessageQueue。同时,View的post方法会借助AttachInfo与Handler交互,将任务放入HandlerActionQueue并由UI线程执行。
摘要由CSDN通过智能技术生成

网上有很多关于Handler的帖子,但是看了那么多,不自己亲自分析一下,还是虚得很

哪些地方用到了Handler?

1.

runOnUiThread(Runnable action)

我们在Activity中写处理逻辑的时候,经常会用到这个方法,用来保证代码在UI线程中执行。
来看看它是怎么实现的:

 /**
     * Runs the specified action on the UI thread. If the current thread is the UI
     * thread, then the action is executed immediately. If the current thread is
     * not the UI thread, the action is posted to the event queue of the UI thread.
     *
     * @param action the action to run on the UI thread
     */
    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

可以看到,如果当前线程是UI线程,则调用Handler的post方法。否则直接运行。
那么就来看看Handler的post方法:


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值