Android應用程式啟動過程原始碼分析
前文簡要介紹了Android應用程式的Activity的啟動過程。在Android系統中,應用程式是由Activity組成的,因此,應用程式的啟動過程實際上就是應用程式中的預設Activity的啟動過程,本文將詳細分析應用程式框架層的原始碼,瞭解Android應用程式的啟動過程。
在上一篇文章Android應用程式的Activity啟動過程簡要介紹和學習計劃中,我們舉例子說明了啟動Android應用程式中的Activity的兩種情景,其中,在手機螢幕中點選應用程式圖示的情景就會引發Android應用程式中的預設Activity的啟動,從而把應用程式啟動起來。這種啟動方式的特點是會啟動一個新的程式來載入相應的Activity。這裡,我們繼續以這個例子為例來說明Android應用程式的啟動過程,即MainActivity的啟動過程。
MainActivity的啟動過程如下圖所示:
下面詳細分析每一步是如何實現的。
Step 1. Launcher.startActivitySafely
在Android系統中,應用程式是由Launcher啟動起來的,其實,Launcher本身也是一個應用程式,其它的應用程式安裝後,就會Launcher的介面上出現一個相應的圖示,點選這個圖示時,Launcher就會對應的應用程式啟動起來。
Launcher的原始碼工程在packages/apps/Launcher2目錄下,負責啟動其它應用程式的原始碼實現在src/com/android/launcher2/Launcher.java檔案中:
- /**
- * Default launcher application.
- */
- public final class Launcher extends Activity
- implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher {
- ......
- /**
- * Launches the intent referred by the clicked shortcut.
- *
- * @param v The view representing the clicked shortcut.
- */
- public void onClick(View v) {
- Object tag = v.getTag();
- if (tag instanceof ShortcutInfo) {
- // Open shortcut
- final Intent intent = ((ShortcutInfo) tag).intent;
- int[] pos = new int[2];
- v.getLocationOnScreen(pos);
- intent.setSourceBounds(new Rect(pos[0], pos[1],
- pos[0] + v.getWidth(), pos[1] + v.getHeight()));
- startActivitySafely(intent, tag);
- } else if (tag instanceof FolderInfo) {
- ......
- } else if (v == mHandleView) {
- ......
- }
- }
- void startActivitySafely(Intent intent, Object tag) {
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- try {
- startActivity(intent);
- } catch (ActivityNotFoundException e) {
- ......
- } catch (SecurityException e) {
- ......
- }
- }
- ......
- }
- <activity android:name=".MainActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
Step 2. Activity.startActivity
在Step 1中,我們看到,Launcher繼承於Activity類,而Activity類實現了startActivity函式,因此,這裡就呼叫了Activity.startActivity函式,它實現在frameworks/base/core/java/android/app/Activity.java檔案中:
- public class Activity extends ContextThemeWrapper
- implements LayoutInflater.Factory,
- Window.Callback, KeyEvent.Callback,
- OnCreateContextMenuListener, ComponentCallbacks {
- ......
- @Override
- public void startActivity(Intent intent) {
- startActivityForResult(intent, -1);
- }
- ......
- }
Step 3. Activity.startActivityForResult
這個函式也是實現在frameworks/base/core/java/android/app/Activity.java檔案中:
- public class Activity extends ContextThemeWrapper
- implements LayoutInflater.Factory,
- Window.Callback, KeyEvent.Callback,
- OnCreateContextMenuListener, ComponentCallbacks {
- ......
- public void startActivityForResult(Intent intent, int requestCode) {
- if (mParent == null) {
- Instrumentation.ActivityResult ar =
- mInstrumentation.execStartActivity(
- this, mMainThread.getApplicationThread(), mToken, this,
- intent, requestCode);
- ......
- } else {
- ......
- }
- ......
- }
這裡的mMainThread也是Activity類的成員變數,它的型別是ActivityThread,它代表的是應用程式的主執行緒,我們在Android系統在新程式中啟動自定義服務過程(startService)的原理分析一文中已經介紹過了。這裡通過mMainThread.getApplicationThread獲得它裡面的ApplicationThread成員變數,它是一個Binder物件,後面我們會看到,ActivityManagerService會使用它來和ActivityThread來進行程式間通訊。這裡我們需注意的是,這裡的mMainThread代表的是Launcher應用程式執行的程式。
這裡的mToken也是Activity類的成員變數,它是一個Binder物件的遠端介面。
Step 4. Instrumentation.execStartActivity
這個函式定義在frameworks/base/core/java/android/app/Instrumentation.java檔案中:
- public class Instrumentation {
- ......
- public ActivityResult execStartActivity(
- Context who, IBinder contextThread, IBinder token, Activity target,
- Intent intent, int requestCode) {
- IApplicationThread whoThread = (IApplicationThread) contextThread;
- if (mActivityMonitors != null) {
- ......
- }
- try {
- int result = ActivityManagerNative.getDefault()
- .startActivity(whoThread, intent,
- intent.resolveTypeIfNeeded(who.getContentResolver()),
- null, 0, token, target != null ? target.mEmbeddedID : null,
- requestCode, false, false);
- ......
- } catch (RemoteException e) {
- }
- return null;
- }
- ......
- }
這裡的intent.resolveTypeIfNeeded返回這個intent的MIME型別,在這個例子中,沒有AndroidManifest.xml設定MainActivity的MIME型別,因此,這裡返回null。
這裡的target不為null,但是target.mEmbddedID為null,我們不用關注。
Step 5. ActivityManagerProxy.startActivity
這個函式定義在frameworks/base/core/java/android/app/ActivityManagerNative.java檔案中:
- class ActivityManagerProxy implements IActivityManager
- {
- ......
- public int startActivity(IApplicationThread caller, Intent intent,
- String resolvedType, Uri[] grantedUriPermissions, int grantedMode,
- IBinder resultTo, String resultWho,
- int requestCode, boolean onlyIfNeeded,
- boolean debug) throws RemoteException {
- Parcel data = Parcel.obtain();
- Parcel reply = Parcel.obtain();
- data.writeInterfaceToken(IActivityManager.descriptor);
- data.writeStrongBinder(caller != null ? caller.asBinder() : null);
- intent.writeToParcel(data, 0);
- data.writeString(resolvedType);
- data.writeTypedArray(grantedUriPermissions, 0);
- data.writeInt(grantedMode);
- data.writeStrongBinder(resultTo);
- data.writeString(resultWho);
- data.writeInt(requestCode);
- data.writeInt(onlyIfNeeded ? 1 : 0);
- data.writeInt(debug ? 1 : 0);
- mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
- reply.readException();
- int result = reply.readInt();
- reply.recycle();
- data.recycle();
- return result;
- }
- ......
- }
Step 6. ActivityManagerService.startActivity
上一步Step 5通過Binder驅動程式就進入到ActivityManagerService的startActivity函式來了,它定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java檔案中:
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ......
- public final int startActivity(IApplicationThread caller,
- Intent intent, String resolvedType, Uri[] grantedUriPermissions,
- int grantedMode, IBinder resultTo,
- String resultWho, int requestCode, boolean onlyIfNeeded,
- boolean debug) {
- return mMainStack.startActivityMayWait(caller, intent, resolvedType,
- grantedUriPermissions, grantedMode, resultTo, resultWho,
- requestCode, onlyIfNeeded, debug, null, null);
- }
- ......
- }
Step 7. ActivityStack.startActivityMayWait
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- final int startActivityMayWait(IApplicationThread caller,
- Intent intent, String resolvedType, Uri[] grantedUriPermissions,
- int grantedMode, IBinder resultTo,
- String resultWho, int requestCode, boolean onlyIfNeeded,
- boolean debug, WaitResult outResult, Configuration config) {
- ......
- boolean componentSpecified = intent.getComponent() != null;
- // Don't modify the client's object!
- intent = new Intent(intent);
- // Collect information about the target of the Intent.
- ActivityInfo aInfo;
- try {
- ResolveInfo rInfo =
- AppGlobals.getPackageManager().resolveIntent(
- intent, resolvedType,
- PackageManager.MATCH_DEFAULT_ONLY
- | ActivityManagerService.STOCK_PM_FLAGS);
- aInfo = rInfo != null ? rInfo.activityInfo : null;
- } catch (RemoteException e) {
- ......
- }
- if (aInfo != null) {
- // Store the found target back into the intent, because now that
- // we have it we never want to do this again. For example, if the
- // user navigates back to this point in the history, we should
- // always restart the exact same activity.
- intent.setComponent(new ComponentName(
- aInfo.applicationInfo.packageName, aInfo.name));
- ......
- }
- synchronized (mService) {
- int callingPid;
- int callingUid;
- if (caller == null) {
- ......
- } else {
- callingPid = callingUid = -1;
- }
- mConfigWillChange = config != null
- && mService.mConfiguration.diff(config) != 0;
- ......
- if (mMainStack && aInfo != null &&
- (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
- ......
- }
- int res = startActivityLocked(caller, intent, resolvedType,
- grantedUriPermissions, grantedMode, aInfo,
- resultTo, resultWho, requestCode, callingPid, callingUid,
- onlyIfNeeded, componentSpecified);
- if (mConfigWillChange && mMainStack) {
- ......
- }
- ......
- if (outResult != null) {
- ......
- }
- return res;
- }
- }
- ......
- }
下面語句對引數intent的內容進行解析,得到MainActivity的相關資訊,儲存在aInfo變數中:
- ActivityInfo aInfo;
- try {
- ResolveInfo rInfo =
- AppGlobals.getPackageManager().resolveIntent(
- intent, resolvedType,
- PackageManager.MATCH_DEFAULT_ONLY
- | ActivityManagerService.STOCK_PM_FLAGS);
- aInfo = rInfo != null ? rInfo.activityInfo : null;
- } catch (RemoteException e) {
- ......
- }
此外,函式開始的地方呼叫intent.getComponent()函式的返回值不為null,因此,這裡的componentSpecified變數為true。
接下去就呼叫startActivityLocked進一步處理了。
Step 8. ActivityStack.startActivityLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- final int startActivityLocked(IApplicationThread caller,
- Intent intent, String resolvedType,
- Uri[] grantedUriPermissions,
- int grantedMode, ActivityInfo aInfo, IBinder resultTo,
- String resultWho, int requestCode,
- int callingPid, int callingUid, boolean onlyIfNeeded,
- boolean componentSpecified) {
- int err = START_SUCCESS;
- ProcessRecord callerApp = null;
- if (caller != null) {
- callerApp = mService.getRecordForAppLocked(caller);
- if (callerApp != null) {
- callingPid = callerApp.pid;
- callingUid = callerApp.info.uid;
- } else {
- ......
- }
- }
- ......
- ActivityRecord sourceRecord = null;
- ActivityRecord resultRecord = null;
- if (resultTo != null) {
- int index = indexOfTokenLocked(resultTo);
- ......
- if (index >= 0) {
- sourceRecord = (ActivityRecord)mHistory.get(index);
- if (requestCode >= 0 && !sourceRecord.finishing) {
- ......
- }
- }
- }
- int launchFlags = intent.getFlags();
- if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
- && sourceRecord != null) {
- ......
- }
- if (err == START_SUCCESS && intent.getComponent() == null) {
- ......
- }
- if (err == START_SUCCESS && aInfo == null) {
- ......
- }
- if (err != START_SUCCESS) {
- ......
- }
- ......
- ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
- intent, resolvedType, aInfo, mService.mConfiguration,
- resultRecord, resultWho, requestCode, componentSpecified);
- ......
- return startActivityUncheckedLocked(r, sourceRecord,
- grantedUriPermissions, grantedMode, onlyIfNeeded, true);
- }
- ......
- }
前面說過,引數resultTo是Launcher這個Activity裡面的一個Binder物件,通過它可以獲得Launcher這個Activity的相關資訊,儲存在sourceRecord變數中。
再接下來,建立即將要啟動的Activity的相關資訊,並儲存在r變數中:
- ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
- intent, resolvedType, aInfo, mService.mConfiguration,
- resultRecord, resultWho, requestCode, componentSpecified);
Step 9. ActivityStack.startActivityUncheckedLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- final int startActivityUncheckedLocked(ActivityRecord r,
- ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
- int grantedMode, boolean onlyIfNeeded, boolean doResume) {
- final Intent intent = r.intent;
- final int callingUid = r.launchedFromUid;
- int launchFlags = intent.getFlags();
- // We'll invoke onUserLeaving before onPause only if the launching
- // activity did not explicitly state that this is an automated launch.
- mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
- ......
- ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
- != 0 ? r : null;
- // If the onlyIfNeeded flag is set, then we can do this if the activity
- // being launched is the same as the one making the call... or, as
- // a special case, if we do not know the caller then we count the
- // current top activity as the caller.
- if (onlyIfNeeded) {
- ......
- }
- if (sourceRecord == null) {
- ......
- } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
- ......
- } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
- || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
- ......
- }
- if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
- ......
- }
- boolean addingToTask = false;
- if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
- (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
- || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
- || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
- // If bring to front is requested, and no result is requested, and
- // we can find a task that was started with this same
- // component, then instead of launching bring that one to the front.
- if (r.resultTo == null) {
- // See if there is a task to bring to the front. If this is
- // a SINGLE_INSTANCE activity, there can be one and only one
- // instance of it in the history, and it is always in its own
- // unique task, so we do a special search.
- ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
- ? findTaskLocked(intent, r.info)
- : findActivityLocked(intent, r.info);
- if (taskTop != null) {
- ......
- }
- }
- }
- ......
- if (r.packageName != null) {
- // If the activity being launched is the same as the one currently
- // at the top, then we need to check if it should only be launched
- // once.
- ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
- if (top != null && r.resultTo == null) {
- if (top.realActivity.equals(r.realActivity)) {
- ......
- }
- }
- } else {
- ......
- }
- boolean newTask = false;
- // Should this be considered a new task?
- if (r.resultTo == null && !addingToTask
- && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
- // todo: should do better management of integers.
- mService.mCurTask++;
- if (mService.mCurTask <= 0) {
- mService.mCurTask = 1;
- }
- r.task = new TaskRecord(mService.mCurTask, r.info, intent,
- (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
- ......
- newTask = true;
- if (mMainStack) {
- mService.addRecentTaskLocked(r.task);
- }
- } else if (sourceRecord != null) {
- ......
- } else {
- ......
- }
- ......
- startActivityLocked(r, newTask, doResume);
- return START_SUCCESS;
- }
- ......
- }
這個intent的標誌值的位Intent.FLAG_ACTIVITY_NO_USER_ACTION沒有置位,因此 ,成員變數mUserLeaving的值為true。
這個intent的標誌值的位Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP也沒有置位,因此,變數notTop的值為null。
由於在這個例子的AndroidManifest.xml檔案中,MainActivity沒有配置launchMode屬值,因此,這裡的r.launchMode為預設值0,表示以標準(Standard,或者稱為ActivityInfo.LAUNCH_MULTIPLE)的方式來啟動這個Activity。Activity的啟動方式有四種,其餘三種分別是ActivityInfo.LAUNCH_SINGLE_INSTANCE、ActivityInfo.LAUNCH_SINGLE_TASK和ActivityInfo.LAUNCH_SINGLE_TOP,具體可以參考官方網站http://developer.android.com/reference/android/content/pm/ActivityInfo.html。
傳進來的引數r.resultTo為null,表示Launcher不需要等這個即將要啟動的MainActivity的執行結果。
由於這個intent的標誌值的位Intent.FLAG_ACTIVITY_NEW_TASK被置位,而且Intent.FLAG_ACTIVITY_MULTIPLE_TASK沒有置位,因此,下面的if語句會被執行:
- if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
- (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
- || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
- || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
- // If bring to front is requested, and no result is requested, and
- // we can find a task that was started with this same
- // component, then instead of launching bring that one to the front.
- if (r.resultTo == null) {
- // See if there is a task to bring to the front. If this is
- // a SINGLE_INSTANCE activity, there can be one and only one
- // instance of it in the history, and it is always in its own
- // unique task, so we do a special search.
- ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
- ? findTaskLocked(intent, r.info)
- : findActivityLocked(intent, r.info);
- if (taskTop != null) {
- ......
- }
- }
- }
接著往下看:
- if (r.packageName != null) {
- // If the activity being launched is the same as the one currently
- // at the top, then we need to check if it should only be launched
- // once.
- ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
- if (top != null && r.resultTo == null) {
- if (top.realActivity.equals(r.realActivity)) {
- ......
- }
- }
- }
執行到這裡,我們知道,要在一個新的Task裡面來啟動這個Activity了,於是新建立一個Task:
- if (r.resultTo == null && !addingToTask
- && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
- // todo: should do better management of integers.
- mService.mCurTask++;
- if (mService.mCurTask <= 0) {
- mService.mCurTask = 1;
- }
- r.task = new TaskRecord(mService.mCurTask, r.info, intent,
- (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
- ......
- newTask = true;
- if (mMainStack) {
- mService.addRecentTaskLocked(r.task);
- }
- }
最後就進入startActivityLocked(r, newTask, doResume)進一步處理了。這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- private final void startActivityLocked(ActivityRecord r, boolean newTask,
- boolean doResume) {
- final int NH = mHistory.size();
- int addPos = -1;
- if (!newTask) {
- ......
- }
- // Place a new activity at top of stack, so it is next to interact
- // with the user.
- if (addPos < 0) {
- addPos = NH;
- }
- // If we are not placing the new activity frontmost, we do not want
- // to deliver the onUserLeaving callback to the actual frontmost
- // activity
- if (addPos < NH) {
- ......
- }
- // Slot the activity into the history stack and proceed
- mHistory.add(addPos, r);
- r.inHistory = true;
- r.frontOfTask = newTask;
- r.task.numActivities++;
- if (NH > 0) {
- // We want to show the starting preview window if we are
- // switching to a new task, or the next activity's process is
- // not currently running.
- ......
- } else {
- // If this is the first activity, don't do any fancy animations,
- // because there is nothing for it to animate on top of.
- ......
- }
- ......
- if (doResume) {
- resumeTopActivityLocked(null);
- }
- }
- ......
- }
這裡傳進來的引數doResume為true,於是呼叫resumeTopActivityLocked進一步操作。
Step 10. Activity.resumeTopActivityLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- /**
- * Ensure that the top activity in the stack is resumed.
- *
- * @param prev The previously resumed activity, for when in the process
- * of pausing; can be null to call from elsewhere.
- *
- * @return Returns true if something is being resumed, or false if
- * nothing happened.
- */
- final boolean resumeTopActivityLocked(ActivityRecord prev) {
- // Find the first activity that is not finishing.
- ActivityRecord next = topRunningActivityLocked(null);
- // Remember how we'll process this pause/resume situation, and ensure
- // that the state is reset however we wind up proceeding.
- final boolean userLeaving = mUserLeaving;
- mUserLeaving = false;
- if (next == null) {
- ......
- }
- next.delayedResume = false;
- // If the top activity is the resumed one, nothing to do.
- if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
- ......
- }
- // If we are sleeping, and there is no resumed activity, and the top
- // activity is paused, well that is the state we want.
- if ((mService.mSleeping || mService.mShuttingDown)
- && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
- ......
- }
- ......
- // If we are currently pausing an activity, then don't do anything
- // until that is done.
- if (mPausingActivity != null) {
- ......
- }
- ......
- // We need to start pausing the current activity so the top one
- // can be resumed...
- if (mResumedActivity != null) {
- ......
- startPausingLocked(userLeaving, false);
- return true;
- }
- ......
- }
- ......
- }
接下來把mUserLeaving的儲存在本地變數userLeaving中,然後重新設定為false,在上面的Step 9中,mUserLeaving的值為true,因此,這裡的userLeaving為true。
這裡的mResumedActivity為Launcher,因為Launcher是當前正被執行的Activity。
當我們處理休眠狀態時,mLastPausedActivity儲存堆疊頂端的Activity,因為當前不是休眠狀態,所以mLastPausedActivity為null。
有了這些資訊之後,下面的語句就容易理解了:
- // If the top activity is the resumed one, nothing to do.
- if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
- ......
- }
- // If we are sleeping, and there is no resumed activity, and the top
- // activity is paused, well that is the state we want.
- if ((mService.mSleeping || mService.mShuttingDown)
- && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
- ......
- }
上面兩個條件都不滿足,因此,在繼續往下執行之前,首先要把當處於Resumed狀態的Activity推入Paused狀態,然後才可以啟動新的Activity。但是在將當前這個Resumed狀態的Activity推入Paused狀態之前,首先要看一下當前是否有Activity正在進入Pausing狀態,如果有的話,當前這個Resumed狀態的Activity就要稍後才能進入Paused狀態了,這樣就保證了所有需要進入Paused狀態的Activity序列處理。
這裡沒有處於Pausing狀態的Activity,即mPausingActivity為null,而且mResumedActivity也不為null,於是就呼叫startPausingLocked函式把Launcher推入Paused狀態去了。
Step 11. ActivityStack.startPausingLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
- if (mPausingActivity != null) {
- ......
- }
- ActivityRecord prev = mResumedActivity;
- if (prev == null) {
- ......
- }
- ......
- mResumedActivity = null;
- mPausingActivity = prev;
- mLastPausedActivity = prev;
- prev.state = ActivityState.PAUSING;
- ......
- if (prev.app != null && prev.app.thread != null) {
- ......
- try {
- ......
- prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
- prev.configChangeFlags);
- ......
- } catch (Exception e) {
- ......
- }
- } else {
- ......
- }
- ......
- }
- ......
- }
函式首先把mResumedActivity儲存在本地變數prev中。在上一步Step 10中,說到mResumedActivity就是Launcher,因此,這裡把Launcher程式中的ApplicationThread物件取出來,通過它來通知Launcher這個Activity它要進入Paused狀態了。當然,這裡的prev.app.thread是一個ApplicationThread物件的遠端介面,通過呼叫這個遠端介面的schedulePauseActivity來通知Launcher進入Paused狀態。
引數prev.finishing表示prev所代表的Activity是否正在等待結束的Activity列表中,由於Laucher這個Activity還沒結束,所以這裡為false;引數prev.configChangeFlags表示哪些config發生了變化,這裡我們不關心它的值。
Step 12. ApplicationThreadProxy.schedulePauseActivity
這個函式定義在frameworks/base/core/java/android/app/ApplicationThreadNative.java檔案中:
- class ApplicationThreadProxy implements IApplicationThread {
- ......
- public final void schedulePauseActivity(IBinder token, boolean finished,
- boolean userLeaving, int configChanges) throws RemoteException {
- Parcel data = Parcel.obtain();
- data.writeInterfaceToken(IApplicationThread.descriptor);
- data.writeStrongBinder(token);
- data.writeInt(finished ? 1 : 0);
- data.writeInt(userLeaving ? 1 :0);
- data.writeInt(configChanges);
- mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
- IBinder.FLAG_ONEWAY);
- data.recycle();
- }
- ......
- }
這個函式通過Binder程式間通訊機制進入到ApplicationThread.schedulePauseActivity函式中。
Step 13. ApplicationThread.schedulePauseActivity
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中,它是ActivityThread的內部類:
- public final class ActivityThread {
- ......
- private final class ApplicationThread extends ApplicationThreadNative {
- ......
- public final void schedulePauseActivity(IBinder token, boolean finished,
- boolean userLeaving, int configChanges) {
- queueOrSendMessage(
- finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
- token,
- (userLeaving ? 1 : 0),
- configChanges);
- }
- ......
- }
- ......
- }
上面說到,這裡的finished值為false,因此,queueOrSendMessage的第一個引數值為H.PAUSE_ACTIVITY,表示要暫停token所代表的Activity,即Launcher。
Step 14. ActivityThread.queueOrSendMessage
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final void queueOrSendMessage(int what, Object obj, int arg1) {
- queueOrSendMessage(what, obj, arg1, 0);
- }
- private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
- synchronized (this) {
- ......
- Message msg = Message.obtain();
- msg.what = what;
- msg.obj = obj;
- msg.arg1 = arg1;
- msg.arg2 = arg2;
- mH.sendMessage(msg);
- }
- }
- ......
- }
Step 15. H.handleMessage
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final class H extends Handler {
- ......
- public void handleMessage(Message msg) {
- ......
- switch (msg.what) {
- ......
- case PAUSE_ACTIVITY:
- handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
- maybeSnapshot();
- break;
- ......
- }
- ......
- }
- ......
- }
這裡呼叫ActivityThread.handlePauseActivity進一步操作,msg.obj是一個ActivityRecord物件的引用,它代表的是Launcher這個Activity。
Step 16. ActivityThread.handlePauseActivity
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final void handlePauseActivity(IBinder token, boolean finished,
- boolean userLeaving, int configChanges) {
- ActivityClientRecord r = mActivities.get(token);
- if (r != null) {
- //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
- if (userLeaving) {
- performUserLeavingActivity(r);
- }
- r.activity.mConfigChangeFlags |= configChanges;
- Bundle state = performPauseActivity(token, finished, true);
- // Make sure any pending writes are now committed.
- QueuedWork.waitToFinish();
- // Tell the activity manager we have paused.
- try {
- ActivityManagerNative.getDefault().activityPaused(token, state);
- } catch (RemoteException ex) {
- }
- }
- }
- ......
- }
Step 17. ActivityManagerProxy.activityPaused
這個函式定義在frameworks/base/core/java/android/app/ActivityManagerNative.java檔案中:
- class ActivityManagerProxy implements IActivityManager
- {
- ......
- public void activityPaused(IBinder token, Bundle state) throws RemoteException
- {
- Parcel data = Parcel.obtain();
- Parcel reply = Parcel.obtain();
- data.writeInterfaceToken(IActivityManager.descriptor);
- data.writeStrongBinder(token);
- data.writeBundle(state);
- mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
- reply.readException();
- data.recycle();
- reply.recycle();
- }
- ......
- }
Step 18. ActivityManagerService.activityPaused
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java檔案中:
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ......
- public final void activityPaused(IBinder token, Bundle icicle) {
- ......
- final long origId = Binder.clearCallingIdentity();
- mMainStack.activityPaused(token, icicle, false);
- ......
- }
- ......
- }
Step 19. ActivityStack.activityPaused
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {
- ......
- ActivityRecord r = null;
- synchronized (mService) {
- int index = indexOfTokenLocked(token);
- if (index >= 0) {
- r = (ActivityRecord)mHistory.get(index);
- if (!timeout) {
- r.icicle = icicle;
- r.haveState = true;
- }
- mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
- if (mPausingActivity == r) {
- r.state = ActivityState.PAUSED;
- completePauseLocked();
- } else {
- ......
- }
- }
- }
- }
- ......
- }
Step 20. ActivityStack.completePauseLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- private final void completePauseLocked() {
- ActivityRecord prev = mPausingActivity;
- ......
- if (prev != null) {
- ......
- mPausingActivity = null;
- }
- if (!mService.mSleeping && !mService.mShuttingDown) {
- resumeTopActivityLocked(prev);
- } else {
- ......
- }
- ......
- }
- ......
- }
Step 21. ActivityStack.resumeTopActivityLokced
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- final boolean resumeTopActivityLocked(ActivityRecord prev) {
- ......
- // Find the first activity that is not finishing.
- ActivityRecord next = topRunningActivityLocked(null);
- // Remember how we'll process this pause/resume situation, and ensure
- // that the state is reset however we wind up proceeding.
- final boolean userLeaving = mUserLeaving;
- mUserLeaving = false;
- ......
- next.delayedResume = false;
- // If the top activity is the resumed one, nothing to do.
- if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
- ......
- return false;
- }
- // If we are sleeping, and there is no resumed activity, and the top
- // activity is paused, well that is the state we want.
- if ((mService.mSleeping || mService.mShuttingDown)
- && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
- ......
- return false;
- }
- .......
- // We need to start pausing the current activity so the top one
- // can be resumed...
- if (mResumedActivity != null) {
- ......
- return true;
- }
- ......
- if (next.app != null && next.app.thread != null) {
- ......
- } else {
- ......
- startSpecificActivityLocked(next, true, true);
- }
- return true;
- }
- ......
- }
Step 22. ActivityStack.startSpecificActivityLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- private final void startSpecificActivityLocked(ActivityRecord r,
- boolean andResume, boolean checkConfig) {
- // Is this activity's application already running?
- ProcessRecord app = mService.getProcessRecordLocked(r.processName,
- r.info.applicationInfo.uid);
- ......
- if (app != null && app.thread != null) {
- try {
- realStartActivityLocked(r, app, andResume, checkConfig);
- return;
- } catch (RemoteException e) {
- ......
- }
- }
- mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
- "activity", r.intent.getComponent(), false);
- }
- ......
- }
- ProcessRecord app = mService.getProcessRecordLocked(r.processName,
- r.info.applicationInfo.uid);
函式最終執行ActivityManagerService.startProcessLocked函式進行下一步操作。
Step 23. ActivityManagerService.startProcessLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java檔案中:
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ......
- final ProcessRecord startProcessLocked(String processName,
- ApplicationInfo info, boolean knownToBeDead, int intentFlags,
- String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
- ProcessRecord app = getProcessRecordLocked(processName, info.uid);
- ......
- String hostingNameStr = hostingName != null
- ? hostingName.flattenToShortString() : null;
- ......
- if (app == null) {
- app = new ProcessRecordLocked(null, info, processName);
- mProcessNames.put(processName, info.uid, app);
- } else {
- // If this is a new package in the process, add the package to the list
- app.addPackage(info.packageName);
- }
- ......
- startProcessLocked(app, hostingType, hostingNameStr);
- return (app.pid != 0) ? app : null;
- }
- ......
- }
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ......
- private final void startProcessLocked(ProcessRecord app,
- String hostingType, String hostingNameStr) {
- ......
- try {
- int uid = app.info.uid;
- int[] gids = null;
- try {
- gids = mContext.getPackageManager().getPackageGids(
- app.info.packageName);
- } catch (PackageManager.NameNotFoundException e) {
- ......
- }
- ......
- int debugFlags = 0;
- ......
- int pid = Process.start("android.app.ActivityThread",
- mSimpleProcessManagement ? app.processName : null, uid, uid,
- gids, debugFlags, null);
- ......
- } catch (RuntimeException e) {
- ......
- }
- }
- ......
- }
Step 24. ActivityThread.main
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final void attach(boolean system) {
- ......
- mSystemThread = system;
- if (!system) {
- ......
- IActivityManager mgr = ActivityManagerNative.getDefault();
- try {
- mgr.attachApplication(mAppThread);
- } catch (RemoteException ex) {
- }
- } else {
- ......
- }
- }
- ......
- public static final void main(String[] args) {
- .......
- ActivityThread thread = new ActivityThread();
- thread.attach(false);
- ......
- Looper.loop();
- .......
- thread.detach();
- ......
- }
- }
函式attach最終呼叫了ActivityManagerService的遠端介面ActivityManagerProxy的attachApplication函式,傳入的引數是mAppThread,這是一個ApplicationThread型別的Binder物件,它的作用是用來進行程式間通訊的。
Step 25. ActivityManagerProxy.attachApplication
這個函式定義在frameworks/base/core/java/android/app/ActivityManagerNative.java檔案中:
- class ActivityManagerProxy implements IActivityManager
- {
- ......
- public void attachApplication(IApplicationThread app) throws RemoteException
- {
- Parcel data = Parcel.obtain();
- Parcel reply = Parcel.obtain();
- data.writeInterfaceToken(IActivityManager.descriptor);
- data.writeStrongBinder(app.asBinder());
- mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
- reply.readException();
- data.recycle();
- reply.recycle();
- }
- ......
- }
Step 26. ActivityManagerService.attachApplication
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java檔案中:
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ......
- public final void attachApplication(IApplicationThread thread) {
- synchronized (this) {
- int callingPid = Binder.getCallingPid();
- final long origId = Binder.clearCallingIdentity();
- attachApplicationLocked(thread, callingPid);
- Binder.restoreCallingIdentity(origId);
- }
- }
- ......
- }
Step 27. ActivityManagerService.attachApplicationLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java檔案中:
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ......
- private final boolean attachApplicationLocked(IApplicationThread thread,
- int pid) {
- // Find the application record that is being attached... either via
- // the pid if we are running in multiple processes, or just pull the
- // next app record if we are emulating process with anonymous threads.
- ProcessRecord app;
- if (pid != MY_PID && pid >= 0) {
- synchronized (mPidsSelfLocked) {
- app = mPidsSelfLocked.get(pid);
- }
- } else if (mStartingProcesses.size() > 0) {
- ......
- } else {
- ......
- }
- if (app == null) {
- ......
- return false;
- }
- ......
- String processName = app.processName;
- try {
- thread.asBinder().linkToDeath(new AppDeathRecipient(
- app, pid, thread), 0);
- } catch (RemoteException e) {
- ......
- return false;
- }
- ......
- app.thread = thread;
- app.curAdj = app.setAdj = -100;
- app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
- app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
- app.forcingToForeground = null;
- app.foregroundServices = false;
- app.debugging = false;
- ......
- boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
- ......
- boolean badApp = false;
- boolean didSomething = false;
- // See if the top visible activity is waiting to run in this process...
- ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
- if (hr != null && normalMode) {
- if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
- && processName.equals(hr.processName)) {
- try {
- if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
- didSomething = true;
- }
- } catch (Exception e) {
- ......
- }
- } else {
- ......
- }
- }
- ......
- return true;
- }
- ......
- }
在前面的Step 23中,已經建立了一個ProcessRecord,這裡首先通過pid將它取回來,放在app變數中,然後對app的其它成員進行初始化,最後呼叫mMainStack.realStartActivityLocked執行真正的Activity啟動操作。這裡要啟動的Activity通過呼叫mMainStack.topRunningActivityLocked(null)從堆疊頂端取回來,這時候在堆疊頂端的Activity就是MainActivity了。
Step 28. ActivityStack.realStartActivityLocked
這個函式定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java檔案中:
- public class ActivityStack {
- ......
- final boolean realStartActivityLocked(ActivityRecord r,
- ProcessRecord app, boolean andResume, boolean checkConfig)
- throws RemoteException {
- ......
- r.app = app;
- ......
- int idx = app.activities.indexOf(r);
- if (idx < 0) {
- app.activities.add(r);
- }
- ......
- try {
- ......
- List<ResultInfo> results = null;
- List<Intent> newIntents = null;
- if (andResume) {
- results = r.results;
- newIntents = r.newIntents;
- }
- ......
- app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
- System.identityHashCode(r),
- r.info, r.icicle, results, newIntents, !andResume,
- mService.isNextTransitionForward());
- ......
- } catch (RemoteException e) {
- ......
- }
- ......
- return true;
- }
- ......
- }
Step 29. ApplicationThreadProxy.scheduleLaunchActivity
這個函式定義在frameworks/base/core/java/android/app/ApplicationThreadNative.java檔案中:
- class ApplicationThreadProxy implements IApplicationThread {
- ......
- public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
- ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
- List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
- throws RemoteException {
- Parcel data = Parcel.obtain();
- data.writeInterfaceToken(IApplicationThread.descriptor);
- intent.writeToParcel(data, 0);
- data.writeStrongBinder(token);
- data.writeInt(ident);
- info.writeToParcel(data, 0);
- data.writeBundle(state);
- data.writeTypedList(pendingResults);
- data.writeTypedList(pendingNewIntents);
- data.writeInt(notResumed ? 1 : 0);
- data.writeInt(isForward ? 1 : 0);
- mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
- IBinder.FLAG_ONEWAY);
- data.recycle();
- }
- ......
- }
Step 30. ApplicationThread.scheduleLaunchActivity
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public 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<ResultInfo> pendingResults,
- List<Intent> 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);
- }
- ......
- }
- ......
- }
Step 31. ActivityThread.queueOrSendMessage
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public 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 arg2) {
- synchronized (this) {
- ......
- Message msg = Message.obtain();
- msg.what = what;
- msg.obj = obj;
- msg.arg1 = arg1;
- msg.arg2 = arg2;
- mH.sendMessage(msg);
- }
- }
- ......
- }
- ......
- }
Step 32. H.handleMessage
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final class H extends Handler {
- ......
- public void handleMessage(Message msg) {
- ......
- switch (msg.what) {
- case LAUNCH_ACTIVITY: {
- ActivityClientRecord r = (ActivityClientRecord)msg.obj;
- r.packageInfo = getPackageInfoNoCheck(
- r.activityInfo.applicationInfo);
- handleLaunchActivity(r, null);
- } break;
- ......
- }
- ......
- }
- ......
- }
Step 33. ActivityThread.handleLaunchActivity
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
- ......
- Activity a = performLaunchActivity(r, customIntent);
- if (a != null) {
- r.createdConfig = new Configuration(mConfiguration);
- Bundle oldState = r.state;
- handleResumeActivity(r.token, false, r.isForward);
- ......
- } else {
- ......
- }
- }
- ......
- }
Step 34. ActivityThread.performLaunchActivity
這個函式定義在frameworks/base/core/java/android/app/ActivityThread.java檔案中:
- public final class ActivityThread {
- ......
- private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
- ActivityInfo aInfo = r.activityInfo;
- if (r.packageInfo == null) {
- r.packageInfo = getPackageInfo(aInfo.applicationInfo,
- Context.CONTEXT_INCLUDE_CODE);
- }
- ComponentName component = r.intent.getComponent();
- if (component == null) {
- component = r.intent.resolveActivity(
- mInitialApplication.getPackageManager());
- r.intent.setComponent(component);
- }
- if (r.activityInfo.targetActivity != null) {
- component = new ComponentName(r.activityInfo.packageName,
- r.activityInfo.targetActivity);
- }
- Activity activity = null;
- try {
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(
- cl, component.getClassName(), r.intent);
- r.intent.setExtrasClassLoader(cl);
- if (r.state != null) {
- r.state.setClassLoader(cl);
- }
- } catch (Exception e) {
- ......
- }
- try {
- Application app = r.packageInfo.makeApplication(false, mInstrumentation);
- ......
- if (activity != null) {
- ContextImpl appContext = new ContextImpl();
- appContext.init(r.packageInfo, r.token, this);
- appContext.setOuterContext(activity);
- CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
- Configuration config = new Configuration(mConfiguration);
- ......
- activity.attach(appContext, this, getInstrumentation(), r.token,
- r.ident, app, r.intent, r.activityInfo, title, r.parent,
- r.embeddedID, r.lastNonConfigurationInstance,
- r.lastNonConfigurationChildInstances, config);
- if (customIntent != null) {
- activity.mIntent = customIntent;
- }
- r.lastNonConfigurationInstance = null;
- r.lastNonConfigurationChildInstances = null;
- activity.mStartedActivity = false;
- int theme = r.activityInfo.getThemeResource();
- if (theme != 0) {
- activity.setTheme(theme);
- }
- activity.mCalled = false;
- mInstrumentation.callActivityOnCreate(activity, r.state);
- ......
- r.activity = activity;
- r.stopped = true;
- if (!r.activity.mFinished) {
- activity.performStart();
- r.stopped = false;
- }
- if (!r.activity.mFinished) {
- if (r.state != null) {
- mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
- }
- }
- if (!r.activity.mFinished) {
- activity.mCalled = false;
- mInstrumentation.callActivityOnPostCreate(activity, r.state);
- if (!activity.mCalled) {
- throw new SuperNotCalledException(
- "Activity " + r.intent.getComponent().toShortString() +
- " did not call through to super.onPostCreate()");
- }
- }
- }
- r.paused = true;
- mActivities.put(r.token, r);
- } catch (SuperNotCalledException e) {
- ......
- } catch (Exception e) {
- ......
- }
- return activity;
- }
- ......
- }
函式前面是收集要啟動的Activity的相關資訊,主要package和component資訊:
- ActivityInfo aInfo = r.activityInfo;
- if (r.packageInfo == null) {
- r.packageInfo = getPackageInfo(aInfo.applicationInfo,
- Context.CONTEXT_INCLUDE_CODE);
- }
- ComponentName component = r.intent.getComponent();
- if (component == null) {
- component = r.intent.resolveActivity(
- mInitialApplication.getPackageManager());
- r.intent.setComponent(component);
- }
- if (r.activityInfo.targetActivity != null) {
- component = new ComponentName(r.activityInfo.packageName,
- r.activityInfo.targetActivity);
- }
- Activity activity = null;
- try {
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(
- cl, component.getClassName(), r.intent);
- r.intent.setExtrasClassLoader(cl);
- if (r.state != null) {
- r.state.setClassLoader(cl);
- }
- } catch (Exception e) {
- ......
- }
- Application app = r.packageInfo.makeApplication(false, mInstrumentation);
- activity.attach(appContext, this, getInstrumentation(), r.token,
- r.ident, app, r.intent, r.activityInfo, title, r.parent,
- r.embeddedID, r.lastNonConfigurationInstance,
- r.lastNonConfigurationChildInstances, config);
- mInstrumentation.callActivityOnCreate(activity, r.state);
Step 35. MainActivity.onCreate
這個函式定義在packages/experimental/Activity/src/shy/luo/activity/MainActivity.java檔案中,這是我們自定義的app工程檔案:
- public class MainActivity extends Activity implements OnClickListener {
- ......
- @Override
- public void onCreate(Bundle savedInstanceState) {
- ......
- Log.i(LOG_TAG, "Main Activity Created.");
- }
- ......
- }
整個應用程式的啟動過程要執行很多步驟,但是整體來看,主要分為以下五個階段:
一. Step1 - Step 11:Launcher通過Binder程式間通訊機制通知ActivityManagerService,它要啟動一個Activity;
二. Step 12 - Step 16:ActivityManagerService通過Binder程式間通訊機制通知Launcher進入Paused狀態;
三. Step 17 - Step 24:Launcher通過Binder程式間通訊機制通知ActivityManagerService,它已經準備就緒進入Paused狀態,於是ActivityManagerService就建立一個新的程式,用來啟動一個ActivityThread例項,即將要啟動的Activity就是在這個ActivityThread例項中執行;
四. Step 25 - Step 27:ActivityThread通過Binder程式間通訊機制將一個ApplicationThread型別的Binder物件傳遞給ActivityManagerService,以便以後ActivityManagerService能夠通過這個Binder物件和它進行通訊;
五. Step 28 - Step 35:ActivityManagerService通過Binder程式間通訊機制通知ActivityThread,現在一切準備就緒,它可以真正執行Activity的啟動操作了。
這裡不少地方涉及到了Binder程式間通訊機制,相關資料請參考Android程式間通訊(IPC)機制Binder簡要介紹和學習計劃一文。
這樣,應用程式的啟動過程就介紹完了,它實質上是啟動應用程式的預設Activity,在下一篇文章中,我們將介紹在應用程式內部啟動另一個Activity的過程,即新的Activity與啟動它的Activity將會在同一個程式(Process)和任務(Task)執行,敬請關注。
相關文章
- Android 8.0 原始碼分析 (三) 應用程式程式建立到應用程式啟動的過程Android原始碼
- Android應用程式程式啟動過程Android
- Androd 系統原始碼-3:應用啟動過程的原始碼分析原始碼
- Android系統原始碼分析--Activity啟動過程Android原始碼
- Android系統原始碼分析--Process啟動過程Android原始碼
- Android系統程式Zygote啟動過程的原始碼分析(3)AndroidGo原始碼
- React Native Android 原始碼分析之啟動過程React NativeAndroid原始碼
- Android原始碼(二)應用程式啟動Android原始碼
- Spring啟動過程——原始碼分析Spring原始碼
- Android系統原始碼分析–Zygote和SystemServer啟動過程Android原始碼GoServer
- Android系統原始碼分析--Zygote和SystemServer啟動過程Android原始碼GoServer
- 【Android原始碼】Service的啟動過程Android原始碼
- Spring Boot原始碼分析-啟動過程Spring Boot原始碼
- Netty NioEventLoop 啟動過程原始碼分析NettyOOP原始碼
- Spring MVC 啟動過程原始碼分析SpringMVC原始碼
- Netty入門一:服務端應用搭建 & 啟動過程原始碼分析Netty服務端原始碼
- Android 原始碼分析之旅2 1 IPC以及Service的啟動過程Android原始碼
- laravel 應用層執行過程原始碼分析Laravel原始碼
- Spring啟動過程——原始碼分析(finishBeanFactoryInitialization(beanFactory))Spring原始碼Bean
- Hive原始碼分析(1)——HiveServer2啟動過程Hive原始碼Server
- Spring啟動過程原始碼分析基本概念Spring原始碼
- 從原始碼看微信小程式啟動過程原始碼微信小程式
- 【原始碼】Redis Server啟動過程原始碼RedisServer
- android view draw原始碼過程分析AndroidView原始碼
- Android 8.0 原始碼分析 (一) SystemServer 程式啟動Android原始碼Server
- 筆記-iOS應用程式的啟動過程筆記iOS
- [原始碼分析] 訊息佇列 Kombu 之 啟動過程原始碼佇列
- 原始碼|HDFS之NameNode:啟動過程原始碼
- 走近原始碼:Redis的啟動過程原始碼Redis
- 以太坊啟動過程原始碼解析原始碼
- 原始碼|HDFS之DataNode:啟動過程原始碼
- SpringBoot 應用程式啟動過程探祕Spring Boot
- Netty服務端啟動過程相關原始碼分析Netty服務端原始碼
- Redis核心原理與實踐--Redis啟動過程原始碼分析Redis原始碼
- 基於原始碼分析apppium服務端啟動過程原始碼APP服務端
- Android應用啟動流程分析Android
- Android Activity啟動流程原始碼分析Android原始碼
- Android原始碼分析:Activity啟動流程Android原始碼