Android應用程序消息處理機制(Looper、Handler)分析(10)
應用程序的主線程準備就好消息隊列并且進入到消息循環(huán)后,其它地方就可以往這個消息隊列中發(fā)送消息了。
我們繼續(xù)以文章開始介紹的Android應用程序啟動過程源代碼分析一文中的應用程序啟動過為例,說明應用程序是如何把消息加入到應用程序的消息隊列中去的。
在Android應用程序啟動過程源代碼分析這篇文章的Step 30中,ActivityManagerService通過調(diào)用ApplicationThread類的scheduleLaunchActivity函 數(shù)通知應用程序。
它可以加載應用程序的默認Activity了,這個函數(shù)定義在frameworks/base/core/java/android /app/ActivityThread.java文件中:
- [java] view plaincopypublic final class ActivityThread {
- ......
- private final class ApplicationThread extends ApplicationThreadNative {
- ......
- // we use token to identify this activity without having to send the
- // activity itself back to the activity manager. (matters more with
- ipc)
- public final void scheduleLaunchActivity(Intent intent, IBinder token, int
- ident,
- ActivityInfo info, Bundle state, List pendingResults,
- List pendingNewIntents, boolean notResumed, boolean isForward)
- {
- ActivityClientRecord r = new ActivityClientRecord();
- r.token = token;
- r.ident = ident;
- r.intent = intent;
- r.activityInfo = info;
- r.state = state;
- r.pendingResults = pendingResults;
- r.pendingIntents = pendingNewIntents;
- r.startsNotResumed = notResumed;
- r.isForward = isForward;
- queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
- }
- ......
- }
- ......
- }
這里把相關(guān)的參數(shù)都封裝成一個ActivityClientRecord對象r,然后調(diào)用queueOrSendMessage函數(shù)來往應用程序的消息隊 列中加入一個新的消息(H.LAUNCH_ACTIVITY),這個函數(shù)定義在frameworks/base/core/java/android /app/ActivityThread.java文件中:
- [java] view plaincopypublic final class ActivityThread {
- ......
- private final class ApplicationThread extends ApplicationThreadNative {
- ......
- // if the thread hasn't started yet, we don't have the handler, so just
- // save the messages until we're ready.
- private final void queueOrSendMessage(int what, Object obj) {
- queueOrSendMessage(what, obj, 0, 0);
- }
- ......
- private final void queueOrSendMessage(int what, Object obj, int arg1, int
- g2) {
- synchronized (this) {
- ......
- Message msg = Message.obtain();
- msg.what = what;
- msg.obj = obj;
- msg.arg1 = arg1;
- msg.arg2 = arg2;
- mH.sendMessage(msg);
- }
- }
- ......
- }
- ......
- }