Handler就是解決線程和線程之間的通信的。
handler的使用場景:1)主線程中使用、2)子線程中使用handler
1)主線程中使用示例:
public class MainActivity extends AppCompatActivity { private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.v("tag","msg what == "+msg.what); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://www.baidu.com") .build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()){ Log.v("tag","success"); handler.sendEmptyMessage(0); } }catch (IOException e){ e.printStackTrace(); } } }).start(); } }
在主線程使用handler很簡單,只需在主線程創建一個handler對象,在子線程通過在主線程創建的handler對象發送Message,在handleMessage()方法中接受這個Message對象進行處理。通過handler很容易的從子線程切換回主線程了。
2)在子線程中使用handler
public class MainActivity extends AppCompatActivity { private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.v("tag","msg what == "+msg.what); } }; private Handler mHandlerThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://www.baidu.com") .build(); //調用Looper.prepare(); Looper.prepare(); mHandlerThread = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; mHandlerThread.sendEmptyMessage(1); //調用Looper.loop() Looper.loop(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()){ Log.v("tag","success"); handler.sendEmptyMessage(0); } }catch (IOException e){ e.printStackTrace(); } } }).start(); } }
在子線程中初始化handler時,需調用looper.prepare()方法。
Handler源碼分析:
Handler的消息處理主要有五個部分組成,Message,Handler,Message Queue,Looper和ThreadLocal。首先簡要的瞭解這些對象的概念
Message:Message是在線程之間傳遞的消息,它可以在內部攜帶少量的數據,用於線程之間交換數據。Message有四個常用的字段,what字段,arg1字段,arg2字段,obj字段。what,arg1,arg2可以攜帶整型數據,obj可以攜帶object對象。
Handler:它主要用於發送和處理消息的發送消息一般使用sendMessage()方法,還有其他的一系列sendXXX的方法,但最終都是調用了sendMessageAtTime方法,除了sendMessageAtFrontOfQueue()這個方法
而發出的消息經過一系列的輾轉處理後,最終會傳遞到Handler的handleMessage方法中。
Message Queue:MessageQueue是消息隊列的意思,它主要用於存放所有通過Handler發送的消息,這部分的消息會一直存在於消息隊列中,等待被處理。每個線程中只會有一個MessageQueue對象。
Looper:每個線程通過Handler發送的消息都保存在,MessageQueue中,Looper通過調用loop()的方法,就會進入到一個無限循環當中,然後每當發現Message Queue中存在一條消息,就會將它取出,並傳遞到Handler的handleMessage()方法中。每個線程中只會有一個Looper對象。
ThreadLocal:MessageQueue對象,和Looper對象在每個線程中都只會有一個對象,怎麼能保證它只有一個對象,就通過ThreadLocal來保存。Thread Local是一個線程內部的數據存儲類,通過它可以在指定線程中存儲數據,數據存儲以後,只有在指定線程中可以獲取到存儲到數據,對於其他線程來說則無法獲取到數據。
Handler的工作機制
1、MessageQueue的工作原理
MessageQueue消息隊列是通過一個單鏈表的數據結構來維護消息列表的。下面主要看enqueueMessage方法和next()方法。如下:
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;
}
可以看出,在這個方法裏主要是根據時間的順序向單鏈表中插入一條消息。
next()方法。如下
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
- 在next方法是一個無限循環的方法,如果有消息返回這條消息並從鏈表中移除,而沒有消息則一直阻塞在這裏。
Looper的工作原理
每個程序都有一個入口,而Android程序是基於java的,java的程序入口是靜態的main函數,因此Android程序的入口也應該爲靜態的main函數,在android程序中這個靜態的main在ActivityThread類中。我們來看一下這個main方法,如下:
public static void main(String[] args) {
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());
Security.addProvider(new AndroidKeyStoreProvider());
// 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"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在main方法中系統調用了 Looper.prepareMainLooper();來創建主線程的Looper以及MessageQueue,並通過Looper.loop()來開啓主線程的消息循環。
來看看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();
}
}
- 可以看到,在這個方法中調用了 prepare(false);方法和 myLooper();方法,我在進入這個兩個方法中,如下:
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));
}
- 在這裏可以看出,sThreadLocal對象保存了一個Looper對象,首先判斷是否已經存在Looper對象了,以防止被調用兩次。
sThreadLocal對象是ThreadLocal類型,因此保證了每個線程中只有一個Looper對象。Looper對象是什麼創建的,我們進入看看,如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
- 可以看出,這裏在Looper構造函數中創建出了一個MessageQueue對象和保存了當前線程。從上面可以看出一個線程中只有一個Looper對象,而Message Queue對象是在Looper構造函數創建出來的,因此每一個線程也只會有一個MessageQueue對象。
對prepare方法還有一個重載的方法:如下
public static void prepare() {
prepare(true);
}
- prepare()僅僅是對prepare(boolean quitAllowed) 的封裝而已,在這裏就很好解釋了在主線程爲什麼不用調用Looper.prepare()方法了。因爲在主線程啓動的時候系統已經幫我們自動調用了Looper.prepare()方法。
在Looper.prepareMainLooper()方法中還調用了一個方法myLooper(),我們進去看看,如下:
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static Looper myLooper() {
return sThreadLocal.get();
}
- 在調用prepare()方法中在當前線程保存一個Looper對象sThreadLocal.set(new Looper(quitAllowed));my Looper()方法就是取出當前線程的Looper對象,保存在sMainLooper引用中。
在main()方法中還調用了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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
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.recycle();
}
}
- 在這個方法裏,進入一個無限循環,不斷的從MessageQueue的next方法獲取消息,而next方法是一個阻塞操作,當沒有消息的時候一直在阻塞,當有消息通過 msg.target.dispatchMessage(msg);這裏的msg.target其實就是發送給這條消息的Handler對象。
我們梳理一下我們在主線程使用Handler的過程。
首先在主線程創建一個Handler對象 ,並重寫handleMessage()方法。然後當在子線程中需要進行更新UI的操作,我們就創建一個Message對象,並通過handler發送這條消息出去。之後這條消息被加入到MessageQueue隊列中等待被處理,通過Looper對象會一直嘗試從Message Queue中取出待處理的消息,最後分發會Handler的handler Message()方法中。
Handler使用的注意事項:
對於Handler的使用依然存在一個問題,由於我們創建的Handler是一個匿名內部類,他會隱式的持有外部類的一個對象(當然內部類也是一樣的),而往往在子線程中是一個耗時的操作,而這個線程也持有Handler的引用,所以這個子線程間接的持有這個外部類的對象。我們假設這個外部類是一個Activity,而有一種情況就是我們的Activity已經銷燬,而子線程仍在運行。由於這個線程持有Activity的對象,所以,在Handler中消息處理完之前,這個Activity就一直得不到回收,從而導致了內存泄露。如果內存泄露過多,則會導致OOM(OutOfMemory),也就是內存溢出。那麼有沒有什麼好的解決辦法呢?
我們可以通過兩種方案來解決,第一種方法我們在Activity銷燬的同時也殺死這個子線程,並且將相對應的Message從消息隊列中移除;第二種方案則是我們創建一個繼承自Handler的靜態內部類。因爲靜態內部類不會持有外部類的對象。可是這時候我們無法去訪問外部類的非靜態的成員變量,也就無法對UI進行操作。這時候我們就需要在這個靜態內部類中使用弱引用的方式去指向這個Activity對象。
下面我們看一下示例代碼。
static class MyHandler extends Handler{
private final WeakReference<MyActivity> mActivity;
public MyHandler(MyActivity activity){
super();
mActivity = new WeakReference<MyActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MyActivity myActivity = mActivity.get();
if (myActivity!=null){
myActivity.textView.setText("123456789");
}
}
}