一、消息循環(huán)過(guò)程
Android應(yīng)用程序進(jìn)程在啟動(dòng)的時(shí)候伟叛,會(huì)在進(jìn)程中加載ActivityThread類略就,并且執(zhí)行這個(gè)類的main函數(shù),應(yīng)用程序的消息循環(huán)過(guò)程就是在這個(gè)main函數(shù)里面實(shí)現(xiàn)的
public static void main(String[] args) {
踢星。澳叉。。。成洗。五督。
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
。瓶殃。充包。。遥椿。基矮。
Looper.loop();
}
首先看Looper.prepareMainLooper函數(shù)
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
final MessageQueue mQueue;
final Thread mThread;
public static void prepareMainLooper() {
prepare(false);標(biāo)注1
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();標(biāo)注2
}
}
標(biāo)注1: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));標(biāo)注3
}
標(biāo)注3:private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
標(biāo)注2:public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
然后看Looper.loop()函數(shù):
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;標(biāo)注4
......
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
......
msg.target.dispatchMessage(msg);標(biāo)注5
......
msg.recycleUnchecked();標(biāo)注6
}
}
標(biāo)注4:MessageQueue對(duì)象Message隊(duì)列
標(biāo)注5:Message的target是Handler
標(biāo)注6:回收Message
二、消息發(fā)送過(guò)程
ActivityManagerService通過(guò)調(diào)用ApplicationThread類的scheduleLaunchActivity函數(shù)通知應(yīng)用程序冠场,它可以加載應(yīng)用程序的默認(rèn)Activity了(ApplicationThread是ActivityThread的內(nèi)部類)
private class ApplicationThread extends ApplicationThreadNative {
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
updateProcessState(procState, false);
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.referrer = referrer;
r.voiceInteractor = voiceInteractor;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;
r.persistentState = persistentState;
r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;
r.startsNotResumed = notResumed;
r.isForward = isForward;
r.profilerInfo = profilerInfo;
r.overrideConfig = overrideConfig;
updatePendingConfiguration(curConfig);
sendMessage(H.LAUNCH_ACTIVITY, r);
}
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
mH是Handler愈捅,Handler.sendMessage最終會(huì)調(diào)用sendMessageAtTime方法:
final MessageQueue mQueue;
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;標(biāo)注7
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);標(biāo)注8
}
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
......
標(biāo)注7:mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
標(biāo)注8:private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;標(biāo)注9:Handler發(fā)送的Message中的target都是Handler本身
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);標(biāo)注10
}
標(biāo)注9:Handler發(fā)送的Message中的target都是Handler本身
標(biāo)注10:MessageQueue的enqueueMessage方法就已經(jīng)將Message信息加入到消息隊(duì)列中了
三、消息的處理
在標(biāo)注5處獲取Message的target也就是當(dāng)前Handler(mH)對(duì)象慈鸠,調(diào)用Handler的dispatchMessage方法蓝谨,最終會(huì)調(diào)用mH的handlerMessage方法:
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
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;