Handler+Looper+MessageQueue深入详解
概述:Android使用消息机制实现线程间的通信,线程通过Looper建立自己的消息循环,MessageQueue是FIFO的消息队列,Looper负责从MessageQueue中取出消息,并且分发到消息指定目标Handler对象。Handler对象绑定到线程的局部变量Looper,封装了发送消息和处理消息的接口。
例子:在介绍原理之前,我们先介绍Android线程通讯的一个例子,这个例子实现点击按钮之后从主线程发送消息”hello”到另外一个名为” CustomThread”的线程。
LooperThreadActivity.java
package com.zhuozhuo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class LooperThreadActivity extends Activity{
private final int MSG_HELLO = 0;
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new CustomThread().start();//新建并启动CustomThread实例
findViewById(R.id.send_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {//点击界面时发送消息
String str = “hello”;
Log.d(“Test”, “MainThread is ready to send msg:” + str);
mHandler.obtainMessage(MSG_HELLO, str).sendToTarget();//发送消息到CustomThread实例
}
});
}
class CustomThread extends Thread {
@Override
public void run() {
//建立消息循环的步骤
Looper.prepare();//1、初始化Looper
mHandler = new Handler(){//2、绑定handler到CustomThread实例的Looper对象
public void handleMessage (Message msg) {//3、定义处理消息的方法
switch(msg.what) {
case MSG_HELLO:
Log.d(“Test”, “CustomThread receive msg:” + (String) msg.obj);
}
}
};
Looper.loop();//4、启动消息循环
}
}
}
main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello”
/>
<Button android:text=”发送消息” android:id=”@+id/send_btn” android:layout_width=”wrap_content” android:layout_height=”wrap_content”></Button>
</LinearLayout>
原理:
我们看到,为一个线程建立消息循环有四个步骤:
1、 初始化Looper
2、 绑定handler到CustomThread实例的Looper对象
3、 定义处理消息的方法
4、 启动消息循环
下面我们以这个例子为线索,深入Android源代码,说明Android Framework是如何建立消息循环,并对消息进行分发的。
1、 初始化Looper : Looper.prepare()
Looper.java
private static final ThreadLocal sThreadLocal = new ThreadLocal();
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException(“Only one Looper may be created per thread”);
}
sThreadLocal.set(new Looper());
}
一个线程在调用Looper的静态方法prepare()时,这个线程会新建一个Looper对象,并放入到线程的局部变量中,而这个变量是不和其他线程共享的(关于ThreadLocal的介绍)。下面我们看看Looper()这个构造函数:
Looper.java
final MessageQueue mQueue;
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
可以看到在Looper的构造函数中,创建了一个消息队列对象mQueue,此时,调用Looper. prepare()的线程就建立起一个消息循环的对象(此时还没开始进行消息循环)。
2、 绑定handler到CustomThread实例的Looper对象 : mHandler= new Handler()
Handler.java
final MessageQueue mQueue;
final Looper mLooper;
public Handler() {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, “The following Handler class should be static or leaks might occur: ” +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
“Can’t create handler inside thread that has not called Looper.prepare()”);
}
mQueue = mLooper.mQueue;
mCallback = null;
}
Handler通过mLooper = Looper.myLooper();绑定到线程的局部变量Looper上去,同时Handler通过mQueue =mLooper.mQueue;获得线程的消息队列。此时,Handler就绑定到创建此Handler对象的线程的消息队列上了。
3、定义处理消息的方法:Override public void handleMessage (Message msg){}
子类需要覆盖这个方法,实现接受到消息后的处理方法。
4、启动消息循环 : Looper.loop()
所有准备工作都准备好了,是时候启动消息循环了!Looper的静态方法loop()实现了消息循环。
Looper.java
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
while (true) {
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!= null) me.mLogging.println(
“>>>>> Dispatching to ” + msg.target + ” ”
+ msg.callback + “: ” + msg.what
);
msg.target.dispatchMessage(msg);
if (me.mLogging!= null) me.mLogging.println(
“<<<<< Finished to ” + msg.target + ” ”
+ msg.callback);
// Make sure that during the course of dispatching the
// identity of the thread wasn’t corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(“Looper”, “Thread identity changed from 0x”
+ Long.toHexString(ident) + ” to 0x”
+ Long.toHexString(newIdent) + ” while dispatching to ”
+ msg.target.getClass().getName() + ” ”
+ msg.callback + ” what=” + msg.what);
}
msg.recycle();
}
}
}
while(true)体现了消息循环中的“循环“,Looper会在循环体中调用queue.next()获取消息队列中需要处理的下一条消息。当msg != null且msg.target != null时,调用msg.target.dispatchMessage(msg);分发消息,当分发完成后,调用msg.recycle();回收消息。
msg.target是一个handler对象,表示需要处理这个消息的handler对象。Handler的void dispatchMessage(Message msg)方法如下:
Handler.java
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可见,当msg.callback== null 并且mCallback == null时,这个例子是由handleMessage(msg);处理消息,上面我们说到子类覆盖这个方法可以实现消息的具体处理过程。
总结:从上面的分析过程可知,消息循环的核心是Looper,Looper持有消息队列MessageQueue对象,一个线程可以把Looper设为该线程的局部变量,这就相当于这个线程建立了一个对应的消息队列。Handler的作用就是封装发送消息和处理消息的过程,让其他线程只需要操作Handler就可以发消息给创建Handler的线程。
相关推荐
Android 异步处理 Handler+Looper+MessageQueue深入详解
Message,MessageQueue,Looper,Handler详解
本篇文章是对Handler,Looper与MessageQueue进行了详细的分析介绍,需要的朋友参考下
Message,MessageQueue,Looper,Handler详解[归类].pdf
Message:消息,其中包含了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理。 Handler:处理者,负责Message的发送及处理。使用Handler时,需要实现handleMessage(Message msg)方法...
关联篇:Handler内存泄漏详解及其解决方案 一说到Android的消息机制,自然就会联想到Handler,我们知道Handler是Android消息机制的上层接口,因此我们在开发过程中也只需要和Handler交互即可,很多人认为Handler的...
每个Handler都有对应的Looper,用于不断地从对应的MessageQueue中取出消息处理。 一直以来,觉得MessageQueue应该是Java层的抽象,然而事实上MessageQueue的主要部分在Native层中。 自己对MessageQueue在Native层...
Handler、Looper、Message、MessageQueue基础流程分析 Android性能优化 ListView详解 RecyclerView和ListView的异同 AsyncTask源码分析 插件化技术 自定义控件 事件分发机制 ANR问题 Art和Dalvik的区别 Android关于...
Handler、Looper、Message、MessageQueue基础流程分析 Android性能优化 ListView详解 RecyclerView和ListView的异同 AsyncTask源码分析 插件化技术 自定义控件 事件分发机制 ANR问题 Art和Dalvik的区别 Android关于...
android线程消息机制主要由Handler,Looper,Message和MessageQuene四个部分组成。平常在开发中,我们常用来在子线程中通知...Looper:是消息的循环处理器,它负责从MessageQueue中取出Message对象进行处理。(Looper含有
,这个题目有点意思,对于很多人来说,可能对Thread和Handler很熟悉,主要涉及到Android的消息机制(Handler、Message、Looper、MessageQueue),详见《 从Handler.post(Runnable r)再一次梳理Android的消息机制(以及...
消息处理机制主要对象:Looper,Handler,Message(还有MessageQueue和Runnable) Looper不断从MessageQueue消息队列中取出一个Message,然后传给Handle,如此循环往复,如果队列为空,那么它会进入休眠。 这些类的主要...
Understanding LooperLooper是用于给一个线程添加一个消息队列(MessageQueue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直到线程结束为止。通常情况下不会用到Looper,因为对于Activity,Service...
通俗的来讲就是,使用Handler将子线程的Message放入主线程的Messagequeue中,在主线程使用。 二、学习内容 学习Android的消息机制,我们需要先了解如下内容。 消息的表示:Message 消息队列:MessageQueue 消息...
Android中的异步消息机制分为四个部分:Message、Handler、MessageQueue和Looper。 其中,Message是线程之间传递的消息,其what、arg1、arg2字段可以携带整型数据,obj字段可以携带一个Object对象。 Handler是处理者...
摘要 Android应用程序是通过消息来驱动的,当Android主线程启动时就会在内部创建一个消息队列。...它们分别是MessageQueue和Looper,MessageQueue就是消息队列,Looper负责轮询消息。 简介 我们已经知
Android应用启动时,会默认有一个主线程(UI线程),在这个线程中会关联一个消息队列(MessageQueue),所有的操作都会被封装成消息队列然后交给主线程处理。为了保证主线程不会退出,会将消息队列的操作放在一个死...
关联篇:深入Android的消息机制源码详解-Handler,MessageQueue与Looper关系 关联篇:Handler内存泄漏及其解决方案 本篇我们将来给大家介绍HandlerThread这个类,以前我们在使用线程执行一个耗时任务时总会new一个...
Android系统的消息队列和消息循环都是针对具体线程的,一个线程可以存在(当然也可以不存在)一个消息队列(Message Queue)和一个消息循环(Looper)。Android中除了UI线程(主线程),创建的工作线程默认是没有...