您的位置:首页 > 移动开发 > Android开发

Android中的Handler通信机制源码解析

2016-10-14 21:24 387 查看
ui线程处理消息

private Handler handler=new Handler(){
public void handleMessage(Message msg){
swtich(msg.what){
case x:
int arg1=(int)msg.arg1;    int arg2=(int)msg.arg2;
Bundle bundle=msg.getData();
break;
}
}
}


工作线程发送消息

Message msg=new Message();

Message msg=handler.obtaionMessage();

msg.what=1; 标记消息

msg.arg1 msg.arg2 存储传递整型数据

msg.obj 存储传递Object类型数据

Bundle bundle=new Bundle();

bundle.putInt(key,xx);

…..

msg.setData(bundle);

handler.sendMessage(msg);

Handler通信机制

Handler机制中工作线程和主线程之间通信主要靠收发消息进行通信,工作线程中执行完成耗时操作需要

将结果数据封装到Message消息对象中,由handler进行发送,**handler在哪个线程中创建就与创建线程中

的MessageQueue相关联**,工作线程使用Handler发送消息时就发送到Handler相关联的消息队列中,发送的

message统一由Handler相关联的MessageQueue消息队列管理;主线程中Handler处理消息时,底层会有

Looper对象循环在Handler相关联的MessageQueue消息队列中取出消息交给Handler调用handlerMessage()

方法处理消息。

public class Looper{

// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;  // guarded by Looper.class  当前线程的Looper对象

final MessageQueue mQueue; //消息队列
final Thread mThread;  //线程对象
...
public static void prepare() {
prepare(true);
}

private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}

....
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//Looper构造函数中构建关联的messageQueue
mThread = Thread.currentThread();
}

.....
//循环取消息
public static void loop() {
final Looper me = myLooper();//获取当前线程关联的Looper对象

//如果获取不到当前线程的looper对象则抛出异常提示

if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}

//获取当前Looper对象中的消息队列对象
final MessageQueue queue = me.mQueue;

....

for (;;) {
//取出当前Looper关联的MessageQueue中的消息对象
Message msg = queue.next(); // might block

if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}

....
//如果MessageQueue能够取出消息  将消息派送给msg.target属性进行处理消息
msg.target.dispatchMessage(msg);

....

msg.recycleUnchecked();//回收资源
}
}

......

/**
* Return the Looper object associated with the current thread.  Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

}


Looper的特点:

1.如果线程想要创建 Handler对象并且处理消息 该线程必须是一个Looper线程

2.每个线程最多只能存在一个Looper对象

3.Looper中包含一个MessageQueue消息队列对象

Handler对象在创建(new)时就与当前线程的Looper MessageQueue相关联 这样通过该handler对象发送

和处理消息都是操作关联的MessageQueue中的消息

简单来说:Handler在哪个线程new就是处理哪个线程MessageQueue消息队列中的消息

public class Handler{
....
final MessageQueue mQueue;  //handler相关联的消息队列
final Looper mLooper;     //handler相关联的Looper对象
final Callback mCallback;
...

public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;//全局-局部
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//将Handler类的对象赋值给message的target属性
....
return queue.enqueueMessage(msg, uptimeMillis);
}


//Handler的构造函数


public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
.....
//获取当前线程相关联的Looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//获取looper中包含的messageQueue对象
mCallback = callback;
....
}

//Handler调用post系列的方法
public final boolean post(Runnable r)
{
return  sendMessageDelayed(getPostMessage(r), 0);
}

private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r; //将Runnable对象传递给Message对象中的属性  callback
return m;
}

处理消息
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

/**
Message.sendmessage()的处理

* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}

/** handler.post(new Runnable(){}) 处理
**/
private static void handleCallback(Message message) {
message.callback.run();// runnble.run()
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  handler
相关文章推荐