在Android中 整個系統(tǒng)的“消息機制” “事件傳遞” “反饋機制”就是由Handler來進行統(tǒng)一管理的
作用:
為了避免ANR卷员,我們會通常把 耗時操作放在子線程里面去執(zhí)行绍妨,因為子線程不能更新UI,所以當子線程需要更新的UI的時候就需要借助到安卓的消息機制懈叹,也就是Handler機制了。
-
我們先從Android的啟動類AcitvityThread的main函數(shù)看起
-
我們繼續(xù)深入 Looper.loop();
msg.recycleUnchecked();//這里消息處理完成后 就進行回收
- 進入msg.target.dispatchMessage(msg);看看Handler是怎么處理消息的
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
- 如果msg.callback != null 那么這個callback代表什么呢
public final class Message implements Parcelable {
Runnable callback;//callback代表著一個Runnable
}
//在看看Handler的 handleCallback(msg);就明白
private static void handleCallback(Message message) {
message.callback.run();//這里的run()就是一個回調(diào) 千萬別認為在分線程中執(zhí)行
}
- 根據(jù)以上分析一目了然 我們平時這樣寫的代碼:
//寫法一
new Handler().post(new Runnable() {
@Override
public void run() {//在Hnadler在主線程的時候 run()也在主線程中執(zhí)行
//這里就不用Handler去處理 而是你自己在run()回調(diào)里面處理
}
});
//寫法二
Runnable runnable=new Runnable() {
@Override
public void run() {
//xxxxxx
}
};
new Handler().postDelayed(runnable,1000);
- 分析完handleCallback(msg); 再接著往下走:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {//mCallback是Handler中定義的一個回調(diào)接口
if (mCallback.handleMessage(msg)) {//執(zhí)行回調(diào)方法
return;
}
}
handleMessage(msg);//若以上都為空 則執(zhí)行Handler的handleMessage()方法
}
}
- Handler.Callback
public class Handler {
final Callback mCallback;//接口
public interface Callback {
public boolean handleMessage(Message msg);
}
public void handleMessage(Message msg) { }
}
- 平時代碼寫法:
private Handler handler=new Handler(new Handler.Callback() {
//這里就給Handler的Callback賦值并回調(diào)
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
-
以上是分析了Handler怎么處理消息 再看Handler是如何發(fā)生消息的
public final boolean postAtTime(Runnable r, long uptimeMillis) {
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
//直接發(fā)送消息
public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}
//發(fā)送空消息
public final boolean sendEmptyMessage(int what) {
return sendEmptyMessageDelayed(what, 0);
}
//發(fā)送延遲消息
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
//在某一時間點發(fā)送消息
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;
}
//這里將消息插入MessageQueue隊列中
return enqueueMessage(queue, msg, uptimeMillis);
}
由上得出 Handler不管是以哪種方式發(fā)送消息 最后都由sendMessageAtTime(msg, delayMillis)該方法來處理
--曾經(jīng)面試在這里躺坑了--
- 最后一些建議:
- 創(chuàng)建Message對象的時候這樣創(chuàng)建:
Message message=Message.obtain();
//源碼:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
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();
}
//通過注釋我們就知道這樣創(chuàng)建的Message是從消息池里面獲取的 避免重復(fù)創(chuàng)建對象;
- 分析了發(fā)送消息和處理消息 最后看看系統(tǒng)Handler做了哪些工作
public final class ActivityThread {
final H mH = new H();
private class H extends Handler {
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {//Activity---onStart()
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
case RELAUNCH_ACTIVITY: {//Activity--onRestart
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
handleRelaunchActivity(r);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
case PAUSE_ACTIVITY://Activity--onPause
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
(msg.arg1&2) != 0);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
..........................................//后面的代碼執(zhí)行觀看
}
}
通過以上源碼發(fā)現(xiàn)Android四大組件的生命周期全部都是由Handler進行統(tǒng)一管理的 由此看出Handler在Android中的重要性典鸡。
**針對Looper是如何創(chuàng)建的 以及MessageQueue對Message的入隊和出隊是如何操作的 就放在下一篇文章講解 **