handler消息机制
MessageQueue代码:http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/os/MessageQueue.java/?v=source
Handler代码:
http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/os/Handler.java/?v=source
Looper代码:
http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/os/Looper.java/?v=source
为什么有handler,handler的主要作用是什么?
首先android UI主线程不能进行大量的耗时操作,否则会产生ANR以及不好的UI体验,因此必须通过异步的方式处理耗时的操作,避免耗时的操作阻塞UI主线程。
handler的主要作用是什么呢,主要负责多个线程之间的信息通信,比如子线程中中耗时操作返回结果需要在UI线程进行展示,这时候就需要通过handler来将消息传递到UI线程并刷新UI内容。
handler的消息机制主要牵扯三方面:
- 消息发送者;
- 消息队列;
- 消息处理循环操作。
handler发消息有两种方式:
- send
- sendEmptyMessage(int),发送一个空的消息;
- sendMessage(Message),发送消息,消息中可以携带参数;
- sendMessageAtTime(Message, long),未来某一时间点发送消息;
- sendMessageDelayed(Message, long),延时Nms发送消息。
- post
- post(Runnable),提交计划任务马上执行;
- postAtTime(Runnable, long),提交计划任务在未来的时间点执行;
- postDelayed(Runnable, long),提交计划任务延时Nms执行。
messageQueue:消息队列,对外提供插入和删除的工作,内部存储结构为单链表结构。
messageQueue的两个主要方法:
- enqueueMessage:向消息队列中插入元素;
- next:从消息队列中取出元素,是个无线循环的方法,无消息,阻塞,有消息,返回消息并从消息队列中将消息移除。
looper:用来构建轮训消息队列系统。
线程默认没有looper,使用handler就必须为线程创建looper。
- Looper.prepare()创建Looper;
- Looper.loop()开启消息循环;
- Looper.prepareMainLooper()主线程创建looper;
- quit:直接退出Looper;
- quitSafely:设定退出标志,已有消息处理完以后才会退出。
消息发送:post方式发送消息的方式最后调用的还是sendMessage方式:
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
public final boolean More ...sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
往下走:
public final boolean More ...sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
最后走到这里:
public boolean More ...sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }
调用 enqueueMessage 在消息队列中插入一条消息,在 enqueueMessage总中,会把 msg.target 设置为当前的Handler 对象。
private boolean More ...enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
如下将消息插入消息队列中去。并且可以很明显看出消息队列是线性链表结构。
boolean enqueueMessage(Message msg, long when) { if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w("MessageQueue", e.getMessage(), e); msg.recycle(); return false; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // New head, wake up the event queue if blocked. msg.next = p; mMessages = msg; needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don't have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; }
每个线程只能运行一个looper对象,创建 Looper 的时候,内部会创建一个消息队列MessageQueue;并且looper在线程里面必须先prepare(),再loop来对消息队列messageQueue来进行遍历循环操作。
public static void loop() { final Looper me = myLooper(); //如果looper对象是空的,就提示必须在当前线程通过looper.prepare()来进行创建 if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } //如果looper不为null,就取出消息队列 final MessageQueue queue = me.mQueue; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); //遍历消息队列 for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. //没有消息中断操作,跳出循环 return; } //----------------队列不为null的操作---------------- // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } //----------------队列不为null,分发数据出去---------------- msg.target.dispatchMessage(msg); if (logging != null) { logging.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(TAG, "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.recycleUnchecked(); } }
循环遍历并分发消息出去msg.target.dispatchMessage(msg),切换到创建handler所使用的looper中执行,也就是说将逻辑切换到主线程去:
/** * Handle system messages here. *首先,如果消息的 callback 不是空,便调用 handleCallback 处理。否则判断 Handler 的 mCallback 是否为空,不为空则调用它的 handleMessage方法。如果仍然为空,才调用 Handler 自身的 handleMessage,也就是我们创建 Handler 时重写的方法 */ public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } //回调handler的handleMessage(msg)方法,从而接收数据 handleMessage(msg); } }
额,先写到这,明天继续更新。
hander的相关问题的延伸:
handler在实际开发中常见的问题就是内存泄漏的问题了:
常见的写法:
private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case UPDATE_TEXTVIEW: updateTextView(); break; default: break; } } };
1,在Java中,非静态的内部类和匿名内部类都会隐式地持有其外部类的引用,静态的内部类不会持有外部类的引用,通过将类声明为静态的,解决持有外部类引用的问题;
2,android主线程有looper,looper处理MessageQueue消息队列数据的进进出出,Message
添加到消息队列中的时候Message(排队的Message)
会持有当前Handler
引用,处理消息,并在ui界面上进行结果展示或者toast()或者dialog对话框弹出,就会产生MessageQueue 到 Message 到 Handler 到 Activity的引用链。
为了解决静态内部类无法操作外部类的内容,将activity作为弱引用引入,这样就就可以避免引用的问题,有可以对外部类的方法进行调用。
那么如何解决呢?
private Handler handler = new MyHandler( BackPasswordActivity.this ); private class MyHandler extends Handler { private WeakReference<Activity> mActivity; public MyHandler(BackPasswordActivity activity) { mActivity = new WeakReference<Activity>( activity ); } @Override public void handleMessage(Message msg) { super.handleMessage( msg ); MainActivity activity = (MainActivity) mActivity.get(); if (activity != null) updateTextView(); } }
还有一种解决方式:WeakHandler
开源库地址:https://github.com/badoo/android-weak-handler
实际项目中使用:
1,引入:compile 'com.badoo.mobile:android-weak-handler:1.1',当然也可以代码引入,就一个类;
2,代码中的使用:
声明以及在主线程中接收消息,注意和我们的handler的写法的不同:
WeakHandler myHandler = new WeakHandler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 1: //UI操作 if (!StringUtil.isEmpty(tradeNo)) { rechargeStatus(); } break; default: break; } return false; } });
发送消息:
Message message = new Message(); message.what = 1; myHandler.sendMessage(message); //发送message