Android 线程通信(Handler + Message + Looper) 0 - 前言

13 篇文章 0 订阅
12 篇文章 2 订阅

参考:

进程和线程

Android异步消息处理机制完全解析,带你从源码的角度彻底理解

Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系


Android 开发中,可以使用 Handler + Looper + Message 的组合进行线程通信

当前运行环境:Android 7.1.1 API Level 25

本次学习暂不涉及进程操作


主要内容:

  1. 简单使用例子
  2. Message
  3. Looper
  4. Handler
  5. Android 封装的 Handler 操作
  6. HandlerThread

简单使用例子

首先创建子类 MyHandler 继承 Handler,并实现函数 handleMessage

class MyHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        Log.e(TAG, "handleMessage: " + Thread.currentThread().getName());
    }
}

MainActivity 实例化 MyHandler,创建线程,然后在线程中使用 MyHandler 对象发送消息:

final MyHandler handler = new MyHandler();

new Thread(new Runnable() {
    @Override
    public void run() {
        Log.e(TAG, "run: " + Thread.currentThread().getName());
        handler.sendEmptyMessage(1);
    }
}).start();

运行程序,结果如下所示:

这里写图片描述

Handler 在线程中发送消息,最后在 UI 线程中得到消息,实现了线程之间的通信


Message

Looper

Handler


Android 封装的 Handler 操作

Handler + Message + Looper 的异步消息通信机制如下图所示(应该是郭神自己画的吧

这里写图片描述

Android 也封装了几个 Handler 操作:

  • Activity.runOnUiThread(Runnable)
  • View.post(Runnable)
  • View.postDelayed(Runnable, long)

查看其实现:

// we must have a handler before the FragmentController is constructed
final Handler mHandler = new Handler();

/**
 * 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();
    }
}

其实 Activity.runOnUiThread(Runnable) 是调用了自带的 Handlerpost 方法,其作用是让 Runnable 对象运行在主线程

/**
 * <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);
    }
    ...
}

同样也是调用 Handler 对象实现的


HandlerThread

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值