1.活用Android线程间通信的Message机制
1.1.Message
代码在frameworks\base\core\java\android\Os\Message.java中。
Message.obtain函数:有多个obtain函数,主要功能一样,只是参数不一样。作用是从Message Pool中取出一个Message,如果Message Pool中已经没有Message可取则新建一个Message返回,同时用对应的参数给得到的Message对象赋值。
Message Pool:大小为10个;通过Message.mPool->(Message并且Message.next)-> (Message并且Message.next)-> (Message并且Message.next)...构造一个Message Pool。Message Pool的第一个元素直接new出来,然后把Message.mPool(static类的static变量)指向它。其他的元素都是使用完的 Message通过Message的recycle函数清理后放到Message Pool(通过Message Pool最后一个Message的next指向需要回收的Message的方式实现)。下图为Message Pool的结构:
1.2.MessageQueue
MessageQueue里面有一个收到的Message的对列:
MessageQueue.mMessages(static变量)->( Message并且Message.next)-> ( Message并且Message.next)->...,下图为接收消息的消息队列:
上层代码通过Handler的sendMessage等函数放入一个message到MessageQueue里面时最终会调用MessageQueue的 enqueueMessage函数。enqueueMessage根据上面的接收的Message的队列的构造把接收到的Message放入队列中。
MessageQueue的removeMessages函数根据上面的接收的Message的队列的构造把接收到的Message从队列中删除,并且调用对应Message对象的recycle函数把不用的Message放入Message Pool中。
1.3.Looper
Looper对象的创建是通过prepare函数,而且每一个Looper对象会和一个线程关联
Looper对象创建时会创建一个MessageQueue,主线程默认会创建一个Looper从而有MessageQueue,其他线程默认是没有 MessageQueue的不能接收Message,如果需要接收Message则需要通过prepare函数创建一个MessageQueue。具体操作请见示例代码。
prepareMainLooper函数只给主线程调用(系统处理,程序员不用处理),它会调用prepare建立Looper对象和MessageQueue。
1.4.Handler
Handler的构造函数表示Handler会有成员变量指向Looper和MessageQueue,后面我们会看到没什么需要这些引用;至于callback是实现了Callback接口的对象,后面会看到这个对象的作用。
Loop函数从MessageQueue中从前往后取出Message,然后通过Handler的dispatchMessage函数进行消息的处理(可见消息的处理是Handler负责的),消息处理完了以后通过Message对象的recycle函数放到Message Pool中,以便下次使用,通过Pool的处理提供了一定的内存管理从而加速消息对象的获取。至于需要定时处理的消息如何做到定时处理,请见 MessageQueue的next函数,它在取Message来进行处理时通过判断MessageQueue里面的Message是否符合时间要求来决定是否需要把Message取出来做处理,通过这种方式做到消息的定时处理。
Handler类的常用方法
方法签名 |
描 述 |
public void handleMessage (Message msg) |
子类对象通过该方法接收信息 |
public final boolean sendEmptyMessage (int what) |
发送一个只含有 what 值的消息 |
public final boolean sendMessage (Message msg) |
发送消息到 Handler , 通过 handleMessage 方法接收 |
public final boolean hasMessages (int what) |
监测消息队列中是否还 有 what 值的消息 |
public final boolean post (Runnable r) |
将一个线程添加到消息队列 |
获取消息:直接通过Message的obtain方法获取一个Message对象。
- public final Message obtainMessage(int what, int arg1, int arg2, Object obj){
- return Message.obtain(this, what, arg1, arg2, obj);
- }
public final Message obtainMessage(int what, int arg1, int arg2, Object obj){
return Message.obtain(this, what, arg1, arg2, obj);
}
发送消息:通过MessageQueue的enqueueMessage把Message对象放到MessageQueue的接收消息队列中
- public boolean sendMessageAtTime(Message msg, long uptimeMillis){
- boolean sent = false;
- MessageQueue queue = mQueue;
- if (queue != null) {
- msg.target = this;
- sent = queue.enqueueMessage(msg, uptimeMillis);
- } else {
- RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");
- Log.w("Looper", e.getMessage(), e);
- }
- return sent;
- }
public boolean sendMessageAtTime(Message msg, long uptimeMillis){
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this;
sent = queue.enqueueMessage(msg, uptimeMillis);
} else {
RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
线程如何处理MessageQueue中接收的消息:在Looper的loop函数中循环取出MessageQueue的接收消息队列中的消息,然后调用 Hander的dispatchMessage函数对消息进行处理,至于如何处理(相应消息)则由用户指定(三个方法,优先级从高到低:Message里面的Callback,一个实现了Runnable接口的对象,其中run函数做处理工作;Handler里面的mCallback指向的一个实现了 Callback接口的对象,里面的handleMessage进行处理;处理消息Handler对象对应的类继承并实现了其中 handleMessage函数,通过这个实现的handleMessage函数处理消息)。
- public void dispatchMessage(Message msg) {
- if (msg.callback != null) {
- handleCallback(msg);
- } else {
- if (mCallback != null) {
- if (mCallback.handleMessage(msg)) {
- return;
- }
- }
- handleMessage(msg);
- }
- }
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
Runnable说明:Runnable只是一个接口,实现了这个接口的类对应的对象也只是个普通的对象,并不是一个Java中的Thread。Thread类经常使用Runnable,很多人有误解,所以这里澄清一下。
从上可知以下关系图:
其中清理Message是Looper里面的loop函数指把处理过的Message放到Message的Pool里面去,如果里面已经超过最大值10个,则丢弃这个Message对象。
调用Handler是指Looper里面的loop函数从MessageQueue的接收消息队列里面取出消息,然后根据消息指向的Handler对象调用其对应的处理方法。
在Android 中Handler和Message、Thread有着很密切的关系。Handler 主要是负责Message的分发和处理。但是这个Message从哪里来的呢?Message 由一个消息队列进行管理,而消息队列却由一个Looper进行管理。Android系统中Looper负责管理线程的消息队列和消息循环,具体实现请参考Looper的源码。 可以通过Loop.myLooper()得到当前线程的Looper对象,通过Loop.getMainLooper()可以获得当前进程的主线程的 Looper对象。 Android系统的消息队列和消息循环都是针对具体线程的,一个线程可以存在(当然也可以不存在)一个消息队列和一个消息循环(Looper),特定线程的消息只能分发给本线程,不能进行跨线程,跨进程通讯。但是创建的工作线程默认是没有消息循环和消息队列的,如果想让该线程具有消息队列和消息循环,需要在线程中首先调用Looper.prepare()来创建消息队列,然后调用Looper.loop()进入消息循环。
虽说 特定线程的消息只能分发给本线程,不能进行跨线程通讯,但是由于可以通过获得线程的Looper对象来进行曲线的实现不同线程间消息的传递,代码如下:
package com.mytest.handlertest;
import android.app.Activity;
import android.graphics.Color;
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;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class HandlerTest extends Activity implements OnClickListener{
private String TAG = "HandlerTest";
private boolean bpostRunnable = false;
private NoLooperThread noLooperThread = null;
private OwnLooperThread ownLooperThread = null;
private ReceiveMessageThread receiveMessageThread =null;
private Handler mOtherThreadHandler=null;
private EventHandler mHandler = null;
private Button btn1 = null;
private Button btn2 = null;
private Button btn3 = null;
private Button btn4 = null;
private Button btn5 = null;
private Button btn6 = null;
private TextView tv = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(250, 50);
layout.setOrientation(LinearLayout.VERTICAL);
btn1 = new Button(this);
btn1.setId(101);
btn1.setText("message from main thread self");
btn1.setOnClickListener(this);
layout.addView(btn1, params);
btn2 = new Button(this);
btn2.setId(102);
btn2.setText("message from other thread to main thread");
btn2.setOnClickListener(this);
layout.addView(btn2,params);
btn3 = new Button(this);
btn3.setId(103);
btn3.setText("message to other thread from itself");
btn3.setOnClickListener(this);
layout.addView(btn3, params);
btn4 = new Button(this);
btn4.setId(104);
btn4.setText("message with Runnable as callback from other thread to main thread");
btn4.setOnClickListener(this);
layout.addView(btn4, params);
btn5 = new Button(this);
btn5.setId(105);
btn5.setText("main thread's message to other thread");
btn5.setOnClickListener(this);
layout.addView(btn5, params);
btn6 = new Button(this);
btn6.setId(106);
btn6.setText("exit");
btn6.setOnClickListener(this);
layout.addView(btn6, params);
tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setText("");
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.topMargin=10;
layout.addView(tv, params);
setContentView(layout);
receiveMessageThread = new ReceiveMessageThread();
receiveMessageThread.start();
}
class EventHandler extends Handler{
public EventHandler(Looper looper){
super(looper);
}
public EventHandler(){
super();
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());
switch(msg.what){
case 1:
tv.setText((String)msg.obj);
break;
case 2:
tv.setText((String)msg.obj);
noLooperThread.stop();
break;
case 3:
Log.e(TAG,(String)msg.obj);
ownLooperThread.stop();
break;
default:
Log.e(TAG,(String)msg.obj);
break;
}
}
}
class ReceiveMessageThread extends Thread {
@Override
public void run(){
Looper.prepare();
mOtherThreadHandler= new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e(TAG,"-------+>"+(String)msg.obj);
Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());
}
};
Log.e(TAG, "ReceiveMessageThread id:--------+>" + this.getId());
Looper.loop();
}
}
class NoLooperThread extends Thread {
private EventHandler mNoLooperThreadHandler;
@Override
public void run() {
Looper myLooper = Looper.myLooper();
Looper mainLooper= Looper.getMainLooper();
String msgobj;
if(null == myLooper){
mNoLooperThreadHandler = new EventHandler(mainLooper);
msgobj = "NoLooperThread has no looper and handleMessage function executed in main thread!";
} else{
mNoLooperThreadHandler = new EventHandler(myLooper);
msgobj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!";
}
mNoLooperThreadHandler.removeMessages(0);
if(bpostRunnable == false){
Message msg = mNoLooperThreadHandler.obtainMessage(2, 1, 1, msgobj);
mNoLooperThreadHandler.sendMessage(msg);
Log.e(TAG, "NoLooperThread id:--------+>" + this.getId());
}else{
mNoLooperThreadHandler.post(new Runnable(){
public void run() {
tv.setText("update UI through handler post runnalbe mechanism!");
Log.e(TAG, "update UI id:--------+>" + Thread.currentThread().getId());
noLooperThread.stop();
}
});
}
}
}
class OwnLooperThread extends Thread{
private EventHandler mOwnLooperThreadHandler = null;
@Override
public void run() {
Looper.prepare();
Looper myLooper = Looper.myLooper();
Looper mainLooper= Looper.getMainLooper();
String msgobj;
if(null == myLooper){
mOwnLooperThreadHandler = new EventHandler(mainLooper);
msgobj = "OwnLooperThread has no looper and handleMessage function executed in main thread!";
}else{
mOwnLooperThreadHandler = new EventHandler(myLooper);
msgobj = "This is from OwnLooperThread self and handleMessage function executed in NoLooperThread!";
}
mOwnLooperThreadHandler.removeMessages(0);
Message msg = mOwnLooperThreadHandler.obtainMessage(3,1,1,msgobj);
mOwnLooperThreadHandler.sendMessage(msg);
Looper.loop();
}
}
public void onClick(View v) {
switch(v.getId()){
case 101:
Looper looper = Looper.myLooper();
mHandler = new EventHandler(looper);
mHandler.removeMessages(0);
String obj = "This main thread's message and received by itself!";
Message msg = mHandler.obtainMessage(1,1,1,obj);
mHandler.sendMessage(msg);
break;
case 102:
bpostRunnable = false;
noLooperThread = new NoLooperThread();
noLooperThread.start();
break;
case 103:
tv.setText("please look at the error level log for other thread received message");
ownLooperThread = new OwnLooperThread();
ownLooperThread.start();
break;
case 104:
bpostRunnable = true;
noLooperThread = new NoLooperThread();
noLooperThread.start();
break;
case 105:
if(null!=mOtherThreadHandler){
tv.setText("please look at the error level log for other thread received message from main thread");
String msgObj = "message from mainThread";
Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);
mOtherThreadHandler.sendMessage(mainThreadMsg);
}
break;
case 106:
finish();
break;
}
}
}