上篇文章,我们罗列了消息机制中常见的几个概念,如果你还未了解,请先看这篇文章, Android 源码解析Handler处理机制(一)。今天这篇文章从源码的角度来分析Handler处理机制。
通过一个实例来演示消息整个过程。
1. 创建好项目后,我们首先分别在主线程和子线程中创建Handler,
private Handler mHandler1;
private Handler mHandler2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv= (TextView) findViewById(R.id.tv);
btn= (Button) findViewById(R.id.btn);
mHandler1=new Handler();
new Thread(){
@Override
public void run() {
mHandler2=new Handler();
}
}.start();
}
程序运行后,报错了,错误提示“ Can't create handler inside thread that has not called Looper.prepare()”,没有调用“Looper.prepare()”。
定位到错误的地方,是在子线程中创建Handler导致的。奇怪!为何在主线程中不报错呢?(相同的代码),如何你看过上篇文章,就会明白了,那么我们就看看主线程中代码是什么样的逻辑。定位到主线程的入口函数,即ActivityThread的main(String[] args)方法,
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
// 初始化应用中需要使用的系统路径
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
//为应用设置当前用户的CA证书保存的位置
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
//设置进程的名称
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();//创建消息循环
//创建ActivityThread 对象
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();//主线程的Handler
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();//执行消息循环
throw new RuntimeException("Main thread loop unexpectedly exited");
}
该方法第21行代码,“Looper.prepareMainLooper()”貌似和“Looper.prepare()”有关,第37行代码“Looper.loop()”,该方法下面会再仔细分析。接着我们跟踪Looper.prepareMainLooper()该方法,发现它内部其实调用了“Looper.prepare()”方法,该方法比较简单,创建了一个“Looper”对象,并且将该Looper对象设置给ThreadLocal(线程本地变量)对象,并且将状态、数据和当前的线程关联。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper的构造方法中创建了一个消息队列。
接下来,我们回到子线程创建Handler的代码,看看Handler的构造方法,
public Handler(Callback callback, boolean async) {
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();//获取当前的looper对象
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//获取当前的消息队列
mCallback = callback;//设置回调方法
mAsynchronous = async;
}
该方法的12~15行,可以看到我们开始的异常信息是从这里来的,当“mLooper”等于“null”时,就抛异常了,接着我们看看获取mLooper的代码,“ mLooper = Looper.myLooper();”,
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
从ThreadLocal(线程本地变量)对象中获取Looper对象。
综上所述,我们在子线程中创建Handler,需要在创建之前加入“Looper.prepare()”方法。大家可以加入这行代码,然后再运行!应该不会报错了!
通过上面一系列的分析,我们可以知道,“子线程默认不是消息循环的,如果要在子线程中创建Handler,需要明确调用Looper.prepare()方法”。
2. 消息处理。
使用Handler发送、接受消息,
private static final int MSG_WHAT = 101;
TextView tv;
Button btn;
private MyHadler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tv);
btn = (Button) findViewById(R.id.btn);
mHandler = new MyHadler();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateUi();
}
});
}
class MyHadler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_WHAT:
String str = (String) msg.obj;
tv.setText(str);
}
}
}
;
/**
*
*/
private void updateUi() {
new Thread() {
@Override
public void run() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = mHandler.obtainMessage();
message.what = MSG_WHAT;
message.obj = "来自子线程的数据";
mHandler.sendMessage(message);
}
}.start();
}
上面是我们比较常用或者常见的使用Handler的代码,点击按钮后,模拟了一个耗时操作,延时5秒,然后使用Handler发送了一个消息,接着通过Handler的handleMessage()接受该消息。具体的运行效果,就不截图了!下面,通过源码来分析,上面代码的内部流程。
首先,我们看看Handler发送消息,代码中发送消息使用了Handler的sendMessage()方法,
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");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
sendMessageAtTime()获取到消息队列然后调用enqueueMessage()方法,消息队列mQueue是从与Handler关联的Looper获得的。
PS:
Message msg: 消息对象
long delayMillis:消息传递的绝对时间,是以SystemClock.uptimeMillis()时间为基准。其中SystemClock.uptimeMillis()是从开机到现在的毫秒书(手机睡眠的时间不包括在内)
SystemClock.currentThreadTimeMillis(); // 在当前线程中已运行的时间
SystemClock.elapsedRealtime(); // 从开机到现在的毫秒书(手机睡眠(sleep)的时间也包括在内)
SystemClock.sleep(100); // 类似Thread.sleep(100);但是该方法会忽略InterruptedException
SystemClock.setCurrentTimeMillis(1000); // 设置时钟的时间,和System.setCurrentTimeMillis类似
发送消息通过一系列的方法最终都会调用Handler的enqueueMessage()方法,
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
该方法将message的target设置为当前的handler,然后调用了MessageQueue对象的enqueueMessage()方法,
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(TAG, 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;
}
该方法将传递进来的消息对象按照时间顺序进行入队。消息入队完成后,接着就是取消息的过程了。下面我们就要去看看消息是如何被取出的。前面我们提到在ActivityThread的main(String[] args)方法中有一行代码“Looper.loop()”,那么我们看看Looper.loop()方法,
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final 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();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
首先获取当前线程的Looper对象,接着从该Looper对象中拿到消息队列,然后无线循环从消息队列中获取消息,如果有消息则处理,否则处于阻塞状态。第32行代码,“ msg.target.dispatchMessage(msg)”是用来处理消息,“ msg.target”是Handler对象,我们接着看看Handler的dispatchMessage()方法,
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
如果message的callback不等于null,则调用Handler的handleCallback()方法,
private static void handleCallback(Message message) {
message.callback.run();
}
该方法调用了message的callback的run()方法(message.callback其实是一个Runnable对象)。
执行message的callback的run()方法,这不是又开启了一个子线程吗?这能更新UI吗?这一步有关详情请看, 你不知道的Runnable接口,深度解析Runnable接口
否则判断mCallback是否等于“null”,如果不等于“null”,则调用mCallback.handleMessage(msg),mCallback是一个接口,定义了一个方法
public interface Callback {
public boolean handleMessage(Message msg);
}
否则调用Handler的handleMessage()方法,
public void handleMessage(Message msg) {
}
Handler对象默认的handleMessage()方法是空方法。我们通过重写handleMessage()方法就可以获取到发送的消息数据。
相信看到这里,大家应该对消息处理更加明了了!心里也敞亮了!。最后来一张消息处理的流程图,帮助大家理解!
PS:在实际开发中,使用Handler可能会引发内存泄露,那么我们该如何避免呢?
创建一个静态Handler内部类,然后对Handler持有的对象使用弱引用,这样在回收时也可以回收Handler持有的对象,这样虽然避免了Activity泄漏,不过Looper线程的消息队列中还是可能会有待处理的消息,所以我们在Activity的Destroy时或者Stop时应该移除消息队列中的消息。
private MyHandler mHandler=new MyHandler(this);
private static class MyHandler extends Handler{
private WeakReference<Context> mReference;
public MyHandler(Context context) {
mReference = new WeakReference<Context>(context);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity=(MainActivity) mReference.get();
if(activity!=null){
//执行操作
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
推荐文章: Android 更新UI的几种方法。