参考:
Android异步消息处理机制完全解析,带你从源码的角度彻底理解
Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
在 Android
开发中,可以使用 Handler + Looper + Message
的组合进行线程通信
当前运行环境:Android 7.1.1 API Level 25
本次学习暂不涉及进程操作
主要内容:
- 简单使用例子
Message
Looper
Handler
Android
封装的Handler
操作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
线程中得到消息,实现了线程之间的通信
Android
封装的
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)
是调用了自带的 Handler
的 post
方法,其作用是让 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
对象实现的