Handler、Message、Looper、MessageQueue
handler是什么?
Handler是Android提供的一种消息传递机制。
Handler作用:
可以将子线程的数据传递到主线程,实现UI更新,或者两个线程之间进行消息传递。
通常使用方法:
在主线程中新建handler对象,重写handleMessage(Message msg)方法。
然后在子线程中通过handler对象的obtainMessage()方法获取Message对象;
通过handler对象的sendMessage系列方法将Message发送出去;
然后在handleMessage方法中处理发送出来的Message。
前面说了可以在两个子线程中进行通讯简单示例如下:
private Handler handler;
Thread thread1 = new Thread() {
@Override
public void run() {
//Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "thread1 receiver message: " + msg.obj.toString());
}
};
//Looper.loop();
}
};
Thread thread2 = new Thread() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = handler.obtainMessage();
message.obj = "Hi thread1";
handler.sendMessage(message);
}
};
thread1.setName("thread1");
thread1.start();
thread2.setName("thread2");
thread2.start();
在这里我们创建了两个子线程,thread1,thread2,并创建了全局变handler,在thread1中对handler进行初始化,重写handleMessage方法。thread2中通过handler的sendMessage()方法来发送消息,运行一下,看看两个线程是否能够成功通讯。
运行,发现报错了!!
报错log:
/*
AndroidRuntime: FATAL EXCEPTION: thread1
Process: design.wang.com.designpatterns, PID: 20673
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
Can't create handler inside thread that has not called Looper.prepare()
*/
分析报错:这里说我们的handler在thread内部没有调用Looper.prepare();
ok,那就加上呗!运行试试,发现thread1中没有打出任何log,thread2没有能联系上thread1,这是为啥呢?
接下来一步步分析看。
初始化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对象
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 = callback;
mAsynchronous = async;
}
Looper.java
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
这里引入一个ThreadLocal对象,有必要解释一波。
ThreadLocal主要用来保存本地线程的变量,即不同线程可以通过同一个threadLocal对象获取当前线程的局部变量,不会出现数据错乱,这里sThreadLocal存放的是Looper对象。
这里通过一个简单的示例来展示一下ThreadLocal的用法
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threadLocal.set(1);
Thread thread1 = new Thread("thread1") {
@Override
public void run() {
threadLocal.set(2);
Log.e(TAG,"thread1 threadLocal.get():"+threadLocal.get());
}
};
Thread thread2 = new Thread("thread2") {
@Override
public void run() {
threadLocal.set(3);
Log.e(TAG,"thread2 threadLocal.get():"+threadLocal.get());
}
};
thread1.start();
thread2.start();
Log.e(TAG,"main thread threadLocal.get():"+threadLocal.get());
}
}
打印出的log如下
E/MainActivity: main thread threadLocal.get():1
E/MainActivity: thread1 threadLocal.get():2
E/MainActivity: thread2 threadLocal.get():3
可以看出ThreadLocal只是保存了当前线程的变量,即使多线程,也不会数据错乱。
回到正题,这里通过myLooper()方法从sThreadLocal中get(),由于没有调用ThreadLocal.set()方法,此时这里返回的是一个null。
从而导致了上面的报错,到这里可以看看哪里去set()的;
也就是log中提示的Looper.prepare();
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");
}
//set之后就可以取了,不会报错
sThreadLocal.set(new Looper(quitAllowed));
}
到这里报错的原因也就一清二楚了。
通过handler.obtainMessage()方法来创建Message对象。
public final Message obtainMessage()
{
return Message.obtain(this);
}
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
Message在MessageQueue中是通过链表存放的,这里sPool是一个Message的静态变量,缓存了当前的Message对象,通过next指向下一个Message,这里返回的是当前缓存的Message,如果当前的sPool为空,则新建一个Message对象。
Message创建完了,那么下一步就是发送了。
分析sendMessage方法:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
调用sendMessageDelayed(msg, 0);
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
源码中发现发送Message最终调用的都是sendMessageAtTime这个方法;
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//这里看到一个全局变量mQueue;
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(queue, msg, uptimeMillis)这个方法。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//记住这句代码,重要,简单分析下这里将this赋值给了target,this也就是当前的handler
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//这里调用了MessageQueue的enqueueMessage()方法,并传进去两个参数
//msg 即我们的Message对象,uptimeMills就是我们是否对message进行延时处理,这里我们没有延时,即为0.
return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue.java:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {//这里出现了target
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {//判断msg是否已经在使用
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();//回收msg,复用
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;
}
通过上面入队操作之后,将所有加入队列的message按照when的时间大小进行排列,然后依次进行唤醒
到了这里,message都放在了MessageQueue里面,也调用了sendMessage(),为什么thread1中收不到消息呢?
又一个黑人问号!!
到这里我们不禁想起在主线程中直接实例化一个Handler,然后在子线程中发送消息,就直接能再主线程中的handleMessage回调方法中收到Message,而且都没有调用我们之前说的Looper.prepare(),并且都没报错,我们都知道Activity的主线程是ActivityThread,这时我们来探一探ActivityThread的main(),看看究竟还有什么不为人知的秘密?
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// 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
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
/// M: ANR Debug Mechanism
mAnrAppManager.setMessageLogger(Looper.myLooper());
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
呐,果然有秘密,我们看到这行代码
Looper.prepareMainLooper();
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
看到这里是不是恍然大悟了,原来主线程中早已为我们做好了初始化,我们前面也执行了Loop.prepare(),接着往下,我们看到
Looper.loop();
加到上面试试,果然成功了。。
来,话不多说,分析下这个Looper.loop()
public static void loop() {
final Looper me = myLooper();
if (me == null) {//这里发现looper对象不存在的话也会报错
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//省去上面一大堆,来,敲黑板,重点代码来了。
//我们在分析enqueueMessage的时候
//发现msg.target = this;这行代码,即调用了handler中的dispatchMessage()
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
在Loop中,开启了一个死循环,用来取出MessageQueue中的message,然后通过handler中的dispatchMessage进行派发,派发出去后就会对msg进行回收,看到这里我们终于看到了曙光啊,有些小激动,有木有!!
public void dispatchMessage(Message msg) {
//这里如果我们设置了CallBack(Runnable)就会执行handleCallback() 1
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {//如果我们初始化handler的时候初始化了callback,这里就会调用callback的run()2
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//3
}
}
示例1:也就是创建Message的时候给callback赋值,此处的callback也就是runnable,可以通过如下代码进行赋值。
private Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
}
});
源码:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
这里将Runnabale对象赋值给了msg中的callback。
示例2:也就是else中if (mCallback != null),这里的mCallback是Handler中的接口Callback
handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
return false;
}
});
示例3:也就是最后的handleMessage(msg)
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
由上可以看出消息分发是有等级的。
总结
Handler、Message、Looper、MessageQueue 的关系
Handler:负责发送和处理消息。
Message:用来携带发送的消息数据。
MessageQueue:消息队列,队列里面的内容就是Message。
Looper:消息轮巡器,负责不停的从MessageQueue中取Message
在使用Handler时可能会出现内存泄漏
为什么会出现内存泄漏问题呢?
Handler的作用是进行线程间通信的,所以新开启的线程是会持有Handler引用的,如果在Activity等中创建Handler,并且是非静态内部类的形式,就有可能造成内存泄漏。
- 众所周知,非静态内部类会隐式持有外部类的引用,所以当其他线程持有了该Handler,线程没有被销毁,则意味着Activity会一直被Handler持有引用而无法被系统回收。
- 同时,MessageQueue中如果存在未处理完的Message,Message的target也是对Activity等的持有引用,也会造成内存泄漏。
为什么在子线程中通过handler发送消息,会在主线程中收到消息?
创建Message的时候在handler.java中有这么一句代码,msg.target = this;这里的this也就是handler对象,最终也是通过target去dispatchMessage的,这handler对象是在主线程中创建的,所以handleMessage中的操作也是在主线程中执行的,也就解释了为什么可以在子线程中更新UI了。
使用Handler规避内存泄漏问题解决方案
private MyHandler mHandler = new MyHandler(this);
public static class MyHandler extends Handler {
private WeakReference<Activity> activityWeakReference;
public FileLoadHandler(Activity activity) {
activityWeakReference = new WeakReference<DeepCleanActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
Activity activity = activityWeakReference.get();
if(activity != null){
.......
}
}
}