Activity原始碼分析

afxstarx發表於2018-09-02

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

androidxref.com/5.0.0_r2/xr…

1.應用如何啟動的,參考zygote啟動的分析

SystemServer.run ->

mActivityManagerService.systemReady ->

startHomeActivityLocked(mCurrentUserId, "systemReady"); ->

mStackSupervisor.startHomeActivity()

2.Activity內部啟動一個Activity

Activity繼承子ContextThemeWrapper繼承自ContextWrapper繼承自Context

Actvity是在ActivityThread中被建立的:

          反射構造Activity
          
          執行attach方法
          
          呼叫宣告周期函式
複製程式碼

所有的Activity啟動,都最終呼叫到了startActivityForResult。這裡的mParent主要是幹嘛用的呢 如果mParent為null,那麼就直接呼叫mInstrumentation.execStartActivity; 如果mParent不為空,那麼呼叫mParent.startActivityFromChild,而最終也是呼叫到了mInstrumentation.execStartActivity。

3734    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
3735        if (mParent == null) {
3736            Instrumentation.ActivityResult ar =
3737                mInstrumentation.execStartActivity(
3738                    this,
3738                    mMainThread.getApplicationThread()
3738                    mToken, 
3738                    this,
3739                    intent, 
3738                    requestCode, 
3738                    options);
3740            if (ar != null) {
3741                mMainThread.sendActivityResult(
3742                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
3743                    ar.getResultData());
3744            }
3761        } else {
3762           mParent.startActivityFromChild(this, intent, requestCode, options);
3769        }
3773    }
複製程式碼
4284    public void startActivityFromChild(@NonNull Activity child, Intent intent,
4285            int requestCode, @Nullable Bundle options) {
4286        Instrumentation.ActivityResult ar =
4287            mInstrumentation.execStartActivity(
4288                this, mMainThread.getApplicationThread(), mToken, child,
4289                intent, requestCode, options);
4290        if (ar != null) {
4291            mMainThread.sendActivityResult(
4292                mToken, child.mEmbeddedID, requestCode,
4293                ar.getResultCode(), ar.getResultData());
4294        }
4295    }
複製程式碼

呼叫完之後,使用了ActivityThread.sendActivityResult,從mActivities中獲取ActivityClientRecord,首先更新了一下可見性,但是幹嘛用呢? 接著呼叫了mInstrumentation來執行activity的onPause什麼週期;最後分發了result呼叫了activity的onActivityResult。如果Activity已經pause了,那麼不會onReusme,如果沒有pause,那麼會呼叫Activity的onResume。程式碼看一下:

3548    private void handleSendResult(ResultData res) {
3549        ActivityClientRecord r = mActivities.get(res.token);
3551        if (r != null) {
3552            final boolean resumed = !r.paused;
3553            if (!r.activity.mFinished && r.activity.mDecor != null
3554                    && r.hideForNow && resumed) {
3558                updateVisibility(r, true);
3559            }
3560            if (resumed) {
3561                try {
3563                    r.activity.mCalled = false;
3564                    r.activity.mTemporaryPause = true;
3565                    mInstrumentation.callActivityOnPause(r.activity);
3566                    if (!r.activity.mCalled) {
3570                    }
3571                } catch (SuperNotCalledException e) {
3580                }
3581            }
3582            deliverResults(r, res.results);
3587        }
3588    }
複製程式碼

回到關鍵函式mInstrumentation.execStartActivity上來,先從mActivityMonitors中找到目標ActivityMonitor, 幹嘛用的呢,通過註釋看大概是已建立的Activity的快取列表吧,看不太明白先放放;其次呼叫ActivityManagerNative.getDefault().startActivity();

幾個引數分析一下:

who:啟動其他Activity的當前Activity

contextThread:ActivityThread中的mApplicationThread

token:ActivityManagerService中ActivityRecord中傳入的域IApplicationToken.Stub appToken

target:啟動其他Activity的當前Activity

Intent:要啟動的目標intent

requestCode:啟動請求碼

options:啟動額外引數

1458    public ActivityResult execStartActivity(
1459            Context who, IBinder contextThread, IBinder token, Activity target,
1460            Intent intent, int requestCode, Bundle options) {
1461        IApplicationThread whoThread = (IApplicationThread) contextThread;
1462        if (mActivityMonitors != null) {
1463            synchronized (mSync) {
1464                final int N = mActivityMonitors.size();
1465                for (int i=0; i<N; i++) {
1466                    final ActivityMonitor am = mActivityMonitors.get(i);
1467                    if (am.match(who, null, intent)) {
1468                        am.mHits++;
1469                        if (am.isBlocking()) {
1470                            return requestCode >= 0 ? am.getResult() : null;
1471                        }
1472                        break;
1473                    }
1474                }
1475            }
1476        }
1477        try {
1478            intent.migrateExtraStreamToClipData();
1479            intent.prepareToLeaveProcess();
1480            int result = 
1481                ActivityManagerNative.getDefault().startActivity(
1481                       whoThread, 
1481                       who.getBasePackageName(), 
1481                       intent,
1482                       intent.resolveTypeIfNeeded(who.getContentResolver()),
1483                       token, 
1481                       target != null ? target.mEmbeddedID : null,
1484                       requestCode, 
1481                       0, 
1481                       null, 
1481                       options);
1485            checkStartActivityResult(result, intent);
1486        } catch (RemoteException e) {
1487        }
1488        return null;
1489    }
複製程式碼

看看關鍵函式吧ActivityManagerNative.getDefault().startActivity();,根據Binder機制可以知道getDefault其實叫做getProxy更好,得到的是ActivityManagerProxy,實際上就是先利用ServiceManager.getService("activity")得到BinderProxy(保持有底層的BpBinder,最終根據程式內的handle利用IPCThreadState來進行通訊)然後放到了ActivityActivityManagerProxy.mRemote中,因此最終呼叫的是ActivityManagerNative的子類ActivityManagerService的onTransact函式中,即呼叫了ActivityManagerService的startActivity(arg0,...,arg9)。 (Binder通訊需要理解系統從下到上機制,以及Service的註冊過程和時機)

ActivityManagerNative

120    @Override
121    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
122            throws RemoteException {
123        switch (code) {
124        case START_ACTIVITY_TRANSACTION:
125        {
126            data.enforceInterface(IActivityManager.descriptor);
127            IBinder b = data.readStrongBinder();
128            IApplicationThread app = ApplicationThreadNative.asInterface(b);
129            String callingPackage = data.readString();
130            Intent intent = Intent.CREATOR.createFromParcel(data);
131            String resolvedType = data.readString();
132            IBinder resultTo = data.readStrongBinder();
133            String resultWho = data.readString();
134            int requestCode = data.readInt();
135            int startFlags = data.readInt();
136            ProfilerInfo profilerInfo = data.readInt() != 0
137                    ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
138            Bundle options = data.readInt() != 0
139                    ? Bundle.CREATOR.createFromParcel(data) : null;
140            int result = startActivity(app, callingPackage, intent, resolvedType,
141                    resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
142            reply.writeNoException();
143            reply.writeInt(result);
144            return true;
145        }
複製程式碼

ActivityManagerService

3539    @Override
3540    public final int startActivity(IApplicationThread caller, String callingPackage,
3541            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3542            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
3543        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
3544            resultWho, requestCode, startFlags, profilerInfo, options,
3545            UserHandle.getCallingUserId());
3546    }
複製程式碼

ActivityManagerService

3549    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3550            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3551            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
3552        enforceNotIsolatedCaller("startActivity");
3553        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3554                false, ALLOW_FULL_ONLY, "startActivity", null);
3555        // TODO: Switch to user app stacks here.
3556        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
3557                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3558                profilerInfo, null, null, options, userId, null, null);
3559    }
複製程式碼

ActivityStackSupervisor

813    final int startActivityMayWait(IApplicationThread caller, int callingUid,
814            String callingPackage, Intent intent, String resolvedType,
815            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
816            IBinder resultTo, String resultWho, int requestCode, int startFlags,
817            ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
818            Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {
825        // Don't modify the client's object!
826        intent = new Intent(intent);
827
828        // Collect information about the target of the Intent.
829        ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
830                profilerInfo, userId);
831
832        ActivityContainer container = (ActivityContainer)iContainer;
833        synchronized (mService) {
834            final int realCallingPid = Binder.getCallingPid();
835            final int realCallingUid = Binder.getCallingUid();
846            final ActivityStack stack;
847            if (container == null || container.mStack.isOnHomeDisplay()) {
848                stack = getFocusedStack();
849            } else {
850                stack = container.mStack;
851            }
852            stack.mConfigWillChange = config != null
853                    && mService.mConfiguration.diff(config) != 0;
854            if (DEBUG_CONFIGURATION) Slog.v(TAG,
855                    "Starting activity when config will change = " + stack.mConfigWillChange);
856
857            final long origId = Binder.clearCallingIdentity();
926
927            int res = startActivityLocked(caller, intent, resolvedType, aInfo,
928                    voiceSession, voiceInteractor, resultTo, resultWho,
929                    requestCode, callingPid, callingUid, callingPackage,
930                    realCallingPid, realCallingUid, startFlags, options,
931                    componentSpecified, null, container, inTask);
932
933            Binder.restoreCallingIdentity(origId);
934
978            return res;
979        }
980    }
複製程式碼

關鍵函式在927行:startActivityLocked構造了ActivityRecord,然後呼叫startActivityUncheckedLocked

1272    final int startActivityLocked(IApplicationThread caller,
1273            Intent intent, String resolvedType, ActivityInfo aInfo,
1274            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1275            IBinder resultTo, String resultWho, int requestCode,
1276            int callingPid, int callingUid, String callingPackage,
1277            int realCallingPid, int realCallingUid, int startFlags, Bundle options,
1278            boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,
1279            TaskRecord inTask) {
1280        int err = ActivityManager.START_SUCCESS;
1281
1306        ActivityRecord sourceRecord = null;
1307        ActivityRecord resultRecord = null;
1318        ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;
1430
1431        boolean abort = !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
1432                callingPid, resolvedType, aInfo.applicationInfo);
1433
1434        if (mService.mController != null) {
1435            try {
1438                Intent watchIntent = intent.cloneFilter();
1439                abort |= !mService.mController.activityStarting(watchIntent,
1440                        aInfo.applicationInfo.packageName);
1441            } catch (RemoteException e) {
1442                mService.mController = null;
1443            }
1444        }
1457        ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
1458                intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
1459                requestCode, componentSpecified, this, container, options);
1460        if (outActivity != null) {
1461            outActivity[0] = r;
1462        }
1463
1464        final ActivityStack stack = getFocusedStack();
1489
1490        err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
1491                startFlags, true, options, inTask);
1492
1493        if (err < 0) 
1498            notifyActivityDrawnForKeyguard();
1499        }
1500        return err;
1501    }
複製程式碼

看下startActivityUncheckedLocked函式,太長了,得繼續擼程式碼

1574    final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
1575            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
1576            boolean doResume, Bundle options, TaskRecord inTask) {
1577        final Intent intent = r.intent;
1578        final int callingUid = r.launchedFromUid;
1588
1589        final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;
1590        final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;
1591        final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;
1592
1593        int launchFlags = intent.getFlags();
1616
1617        final boolean launchTaskBehind = r.mLaunchTaskBehind
1618                && !launchSingleTask && !launchSingleInstance
1619                && (launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0;
1655        if (!doResume) {
1656            r.delayedResume = true;
1657        }
1658
1659        ActivityRecord notTop =
1660                (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null;
1676
1780
1781        boolean movedHome = false;
1782        ActivityStack targetStack;
1783
1784        intent.setFlags(launchFlags);
1785
1972
1973        if (r.packageName != null) {
1974            // If the activity being launched is the same as the one currently
1975            // at the top, then we need to check if it should only be launched
1976            // once.
1977            ActivityStack topStack = getFocusedStack();
1978            ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop);
1979            if (top != null && r.resultTo == null) {
1980                if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
1981                    if (top.app != null && top.app.thread != null) {
1982                        if ((launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
1983                            || launchSingleTop || launchSingleTask) {
1984                            ActivityStack.logStartActivity(EventLogTags.AM_NEW_INTENT, top,
1985                                    top.task);
1986                            // For paranoia, make sure we have correctly
1987                            // resumed the top activity.
1988                            topStack.mLastPausedActivity = null;
1989                            if (doResume) {
1990                                resumeTopActivitiesLocked();
1991                            }
1992                            ActivityOptions.abort(options);
1993                            if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
1994                                // We don't need to start a new activity, and
1995                                // the client said not to do anything if that
1996                                // is the case, so this is it!
1997                                return ActivityManager.START_RETURN_INTENT_TO_CALLER;
1998                            }
1999                            top.deliverNewIntentLocked(callingUid, r.intent);
2000                            return ActivityManager.START_DELIVERED_TO_TOP;
2001                        }
2002                    }
2003                }
2004            }
2005
2006        } else {
2007            if (r.resultTo != null) {
2008                r.resultTo.task.stack.sendActivityResultLocked(-1, r.resultTo, r.resultWho,
2009                        r.requestCode, Activity.RESULT_CANCELED, null);
2010            }
2011            ActivityOptions.abort(options);
2012            return ActivityManager.START_CLASS_NOT_FOUND;
2013        }
2014
2015        boolean newTask = false;
2016        boolean keepCurTransition = false;
2017
2018        TaskRecord taskToAffiliate = launchTaskBehind && sourceRecord != null ?
2019                sourceRecord.task : null;
2020
2166        mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
2167                intent, r.getUriPermissionsLocked(), r.userId);
2168
2169        if (sourceRecord != null && sourceRecord.isRecentsActivity()) {
2170            r.task.setTaskToReturnTo(RECENTS_ACTIVITY_TYPE);
2171        }
2172        if (newTask) {
2173            EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
2174        }
2175        ActivityStack.logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
2176        targetStack.mLastPausedActivity = null;
2177        targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
2178        if (!launchTaskBehind) {
2179            // Don't set focus on an activity that's going to the back.
2180            mService.setFocusedActivityLocked(r);
2181        }
2182        return ActivityManager.START_SUCCESS;
2183    }
複製程式碼

無法繼續讀下去了,還得準備下理論知識,不然只能最原始的通讀所有程式碼,雖然也能完成閱讀但是效率太低了!

參考:blog.csdn.net/qq_23547831… 裡面的呼叫關係有誤

關注2177行,最終呼叫了targetStack.startActivityLocked

ActivityStack

1960    final void startActivityLocked(ActivityRecord r, boolean newTask,
1961            boolean doResume, boolean keepCurTransition, Bundle options) {
1962        TaskRecord rTask = r.task;
1963        final int taskId = rTask.taskId;
1964        // mLaunchTaskBehind tasks get placed at the back of the task stack.
1965        if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
1966            // Last activity in task had been removed or ActivityManagerService is reusing task.
1967            // Insert or replace.
1968            // Might not even be in.
1969            insertTaskAtTop(rTask);
1970            mWindowManager.moveTaskToTop(taskId);
1971        }
1972        TaskRecord task = null;
2021        task = r.task;
2022
2023        // Slot the activity into the history stack and proceed
2024        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,
2025                new RuntimeException("here").fillInStackTrace());
2026        task.addActivityToTop(r);
2027        task.setFrontOfTask();
2028
2029        r.putInHistory();
2030        if (!isHomeStack() || numActivities() > 0) {
2034            boolean showStartingIcon = newTask;
2035            ProcessRecord proc = r.app;
2036            if (proc == null) {
2037                proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
2038            }
2039            if (proc == null || proc.thread == null) {
2040                showStartingIcon = true;
2041            }
2104        } else {
2105            // If this is the first activity, don't do any fancy animations,
2106            // because there is nothing for it to animate on top of.
2107            mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
2108                    r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
2109                    (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0, r.userId,
2110                    r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
2111            ActivityOptions.abort(options);
2112            options = null;
2113        }
2114        if (VALIDATE_TOKENS) {
2115            validateAppTokensLocked();
2116        }
2117
2118        if (doResume) {
2119            mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
2120        }
2121    }
複製程式碼

繼續回到mStackSupervisor中resumeTopActivitiesLocked

2417    boolean resumeTopActivitiesLocked() {
2418        return resumeTopActivitiesLocked(null, null, null);
2419    }
2420
2421    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
2422            Bundle targetOptions) {
2423        if (targetStack == null) {
2424            targetStack = getFocusedStack();
2425        }
2426        // Do targetStack first.
2427        boolean result = false;
2428        if (isFrontStack(targetStack)) {
2429            result = targetStack.resumeTopActivityLocked(target, targetOptions);
2430        }
2431        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
2432            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
2433            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
2434                final ActivityStack stack = stacks.get(stackNdx);
2435                if (stack == targetStack) {
2436                    // Already started above.
2437                    continue;
2438                }
2439                if (isFrontStack(stack)) {
2440                    stack.resumeTopActivityLocked(null);
2441                }
2442            }
2443        }
2444        return result;
2445    }
複製程式碼

ActivityStack

1470    final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
1471        if (inResumeTopActivity) {
1472            // Don't even start recursing.
1473            return false;
1474        }
1475
1476        boolean result = false;
1477        try {
1478            // Protect against recursion.
1479            inResumeTopActivity = true;
1480            result = resumeTopActivityInnerLocked(prev, options);
1481        } finally {
1482            inResumeTopActivity = false;
1483        }
1484        return result;
1485    }
複製程式碼
1487    final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
1495        ActivityRecord parent = mActivityContainer.mParentActivity;
1504
1505        // Find the first activity that is not finishing.
1506        ActivityRecord next = topRunningActivityLocked(null);
1507
1508        // Remember how we'll process this pause/resume situation, and ensure
1509        // that the state is reset however we wind up proceeding.
1510        final boolean userLeaving = mStackSupervisor.mUserLeaving;
1511        mStackSupervisor.mUserLeaving = false;
1512
1526
1527        next.delayedResume = false;
1528
1592        // The activity may be waiting for stop, but that is no longer
1593        // appropriate for it.
1594        mStackSupervisor.mStoppingActivities.remove(next);
1595        mStackSupervisor.mGoingToSleepActivities.remove(next);
1596        next.sleeping = false;
1597        mStackSupervisor.mWaitingVisibleActivities.remove(next);
1598
1638
1639        // We need to start pausing the current activity so the top one
1640        // can be resumed...
1641        boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
1642        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
1643        if (mResumedActivity != null) {
1644            pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
1645            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity);
1646        }
1769
1770        ActivityStack lastStack = mStackSupervisor.getLastStack();
1771        if (next.app != null && next.app.thread != null) {
1772            if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1773
1774            // This activity is now becoming visible.
1775            mWindowManager.setAppVisibility(next.appToken, true);
1902
1903        } else {
1904            // Whoops, need to restart this activity!
1905            if (!next.hasBeenLaunched) {
1906                next.hasBeenLaunched = true;
1907            } else {
1908                if (SHOW_APP_STARTING_PREVIEW) {
1909                    mWindowManager.setAppStartingWindow(
1910                            next.appToken, next.packageName, next.theme,
1911                            mService.compatibilityInfoForPackageLocked(
1912                                    next.info.applicationInfo),
1913                            next.nonLocalizedLabel,
1914                            next.labelRes, next.icon, next.logo, next.windowFlags,
1915                            null, true);
1916                }
1917                if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1918            }
1919            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next);
1920            mStackSupervisor.startSpecificActivityLocked(next, true, true);
1921        }
1922
1923        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
1924        return true;
1925    }
複製程式碼
  A. Activity.startActiviy(intent)
  
  B. Instrumentation.execStartActivity
  
  C. ActivityManagerNative.getDefault().startActivity(...)
  
  D. ActivityManagerService ->  ActivityManagerNative.onTransact 
  
  E. ActivityManagerService.IActivityManager.startActivity
  
  F. mStackSupervisor.startActivityMayWait ->  startActivityLocked
  
  G. mStackSupervisor.startActivityUnchecked
  
  G. targetStack.startActivityLocked
  
  G. mStackSupervisor.resumeTopActivitiesLocked
  
  G. mStackSupervisor.resumeTopActivityInnerLocked
  
  G. targetStack.startPausingLocked
複製程式碼

3.Activity首先執行pause流程

ActivityStack.startPausingLocked() 
IApplicationThread.schudulePauseActivity() 
ActivityThread.sendMessage() 
ActivityThread.H.sendMessage(); 
ActivityThread.H.handleMessage() 
ActivityThread.handlePauseActivity() 
ActivityThread.performPauseActivity() 
Activity.performPause() 
Activity.onPause() 
ActivityManagerNative.getDefault().activityPaused(token) 
ActivityManagerService.activityPaused() 
ActivityStack.activityPausedLocked() 
ActivityStack.completePauseLocked() 
ActivityStack.resumeTopActivitiesLocked() 
ActivityStack.resumeTopActivityLocked() 
ActivityStack.resumeTopActivityInnerLocked() 
ActivityStack.startSpecificActivityLocked
複製程式碼

中間過程就不用細看了,基本上就是ActivityManagerService通過IApplicationThread將pause訊息發給了ActivityThread,然後轉到主執行緒H的handler中接收,通知Activity執行onPause並將通知ActivityManagerService已經處理onPause操作。ActivityManagerService要處理下ActivityStack的一些操作,這些還不是很清楚,最終要呼叫ActivityStatck.startSpecificActivityLocked開始啟動程式了。

4.ActivityThread啟動

ActivityStackSupervisor

1238    void startSpecificActivityLocked(ActivityRecord r,
1239            boolean andResume, boolean checkConfig) {
1240        
1241        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1242                r.info.applicationInfo.uid, true);
1243
1244        r.task.stack.setLaunchTime(r);
1245        // 程式已經啟動了,且繫結了IApplicationThread
1246        if (app != null && app.thread != null) {
1247            try {
1248                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1249                        || !"android".equals(r.info.packageName)) {
1254                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1255                            mService.mProcessStats);
1256                }
1257                realStartActivityLocked(r, app, andResume, checkConfig);
1258                return;
1259            } catch (RemoteException e) {
1262            }
1266        }
1267        // 啟動一個新的程式了哈
1268        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1269                "activity", r.intent.getComponent(), false, false, true);
1270    }
複製程式碼

ActivityManagerService

3076    private final void startProcessLocked(ProcessRecord app,
3077            String hostingType, String hostingNameStr) {
3078        startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
3079                null /* entryPoint */, null /* entryPointArgs */);
3080    }
3081
3082    private final void startProcessLocked(ProcessRecord app, String hostingType,
3083            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs){
3097        mProcessesOnHold.remove(app);
3102
3103        try {
3104            int uid = app.uid;
3106            int[] gids = null;
3107            int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
3189            boolean isActivityProcess = (entryPoint == null);
3190            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
3191            checkTime(startTime, "startProcess: asking zygote to start proc");
3192            Process.ProcessStartResult startResult = Process.start(entryPoint,
3193                    app.processName, uid, uid, gids, debugFlags, mountExternal,
3194                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
3195                    app.info.dataDir, entryPointArgs);
3247            app.setPid(startResult.pid);
3248            app.usingWrapper = startResult.usingWrapper;
3249            app.removed = false;
3250            app.killed = false;
3251            app.killedByAm = false;
3263        } catch (RuntimeException e) {
3265            app.setPid(0);
3271        }
3272    }
複製程式碼

此處建立了一個ProcessRecord!

Process

480    public static final ProcessStartResult start(final String processClass,
481                                  final String niceName,
482                                  int uid, int gid, int[] gids,
483                                  int debugFlags, int mountExternal,
484                                  int targetSdkVersion,
485                                  String seInfo,
486                                  String abi,
487                                  String instructionSet,
488                                  String appDataDir,
489                                  String[] zygoteArgs) {
490        try {
491            return startViaZygote(processClass, niceName, uid, gid, gids,
492                    debugFlags, mountExternal, targetSdkVersion, seInfo,
493                    abi, instructionSet, appDataDir, zygoteArgs);
494        } catch (ZygoteStartFailedEx ex) {
495            Log.e(LOG_TAG,
496                    "Starting VM process through Zygote failed");
497            throw new RuntimeException(
498                    "Starting VM process through Zygote failed", ex);
499        }
500    }
複製程式碼
602    private static ProcessStartResult startViaZygote(final String processClass,
603                                  final String niceName,
604                                  final int uid, final int gid,
605                                  final int[] gids,
606                                  int debugFlags, int mountExternal,
607                                  int targetSdkVersion,
608                                  String seInfo,
609                                  String abi,
610                                  String instructionSet,
611                                  String appDataDir,
612                                  String[] extraArgs)
613                                  throws ZygoteStartFailedEx {
614        synchronized(Process.class) {
615            ArrayList<String> argsForZygote = new ArrayList<String>();
616
617            // --runtime-init, --setuid=, --setgid=,
618            // and --setgroups= must go first
619            argsForZygote.add("--runtime-init");
620            argsForZygote.add("--setuid=" + uid);
621            argsForZygote.add("--setgid=" + gid);
642            argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
643
646
647            // --setgroups is a comma-separated list
648            if (gids != null && gids.length > 0) {
649                StringBuilder sb = new StringBuilder();
650                sb.append("--setgroups=");
651
652                int sz = gids.length;
653                for (int i = 0; i < sz; i++) {
654                    if (i != 0) {
655                        sb.append(',');
656                    }
657                    sb.append(gids[i]);
658                }
659
660                argsForZygote.add(sb.toString());
661            }
662
679            argsForZygote.add(processClass);
680
681            if (extraArgs != null) {
682                for (String arg : extraArgs) {
683                    argsForZygote.add(arg);
684                }
685            }
686
687            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
688        }
689    }
複製程式碼
695    private static ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
696        if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
697            try {
698                primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
699            } catch (IOException ioe) {
700                throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
701            }
702        }
703
704        if (primaryZygoteState.matches(abi)) {
705            return primaryZygoteState;
706        }
716
717        if (secondaryZygoteState.matches(abi)) {
718            return secondaryZygoteState;
719        }
722    }
複製程式碼
536    private static ProcessStartResult zygoteSendArgsAndGetResult(
537            ZygoteState zygoteState, ArrayList<String> args)
538            throws ZygoteStartFailedEx {
539        try {
550            final BufferedWriter writer = zygoteState.writer;
551            final DataInputStream inputStream = zygoteState.inputStream;
552
553            writer.write(Integer.toString(args.size()));
554            writer.newLine();
555
556            int sz = args.size();
557            for (int i = 0; i < sz; i++) {
558                String arg = args.get(i);
559                if (arg.indexOf('\n') >= 0) {
562                }
563                writer.write(arg);
564                writer.newLine();
565            }
566
567            writer.flush();
568
569            // Should there be a timeout on this?
570            ProcessStartResult result = new ProcessStartResult();
571            result.pid = inputStream.readInt();
575            result.usingWrapper = inputStream.readBoolean();
576            return result;
577        } catch (IOException ex) {
578            zygoteState.close();
579            throw new ZygoteStartFailedEx(ex);
580        }
581    }
複製程式碼

最終讓Zygote的socket啟動了android.app.ActivityThread程式,並執行了main函式,並返回了pid。

5.ActivityThread完成Activity的啟動

ActivityManagerService.startProcessLocked() 
Process.start() 
ActivityThread.main() 
ActivityThread.attach() 
ActivityManagerNative.getDefault().attachApplication() 
ActivityManagerService.attachApplication() 
複製程式碼

ActivityThread

5184    public static void main(String[] args) {
5204
5205        Looper.prepareMainLooper();
5206
5207        ActivityThread thread = new ActivityThread();
5208        thread.attach(false);
5214        AsyncTask.init();
5215
5221        Looper.loop();
5224    }
5225}
複製程式碼

分析幾個關鍵的成員變數

mH:作用很簡單即將ApplicationThread執行緒轉到主執行緒中處理

mAppThread:ApplicationThread主要用來接收ActivityManagerService訊息

mActivities:ArrayMap<IBinder, ActivityClientRecord>一個map,用來記錄ActivityRecord成員變數IApplicationToken.Stub appToken

ActivityThread ------------>IApplicationToken------------> ActivityManagerService

                           <------------IApplicationThread<-----------
複製程式碼

問題:token什麼時候傳入ActivityThread的,下面似乎能找到答案,先將IApplicationThread傳入ActivityManagerService中attchApplication,利用IApplicationThread就能傳token到ActivityThread中了。

ActivityThread

5041    private void attach(boolean system) {
5042        sCurrentActivityThread = this;
5043        mSystemThread = system;
5044        if (!system) {
5053            RuntimeInit.setApplicationObject(mAppThread.asBinder());
5054            final IActivityManager mgr = ActivityManagerNative.getDefault();
5055            try {
5055                // 此處開始在ActivityManagerService執行初始化操作
5056                mgr.attachApplication(mAppThread);
5057            } catch (RemoteException ex) {
5059            }
5081        } else {
5086            try {
5055                // 傳入的是false,因此應用的啟動不會走這裡
5092            } catch (Exception e) {
5095            }
5096        }
5127    }
複製程式碼

ActivityManagerService

6249    @Override
6250    public final void attachApplication(IApplicationThread thread) {
6251        synchronized (this) {
6252            int callingPid = Binder.getCallingPid();
6253            final long origId = Binder.clearCallingIdentity();
6254            attachApplicationLocked(thread, callingPid);
6255            Binder.restoreCallingIdentity(origId);
6256        }
6257    }
複製程式碼
6029    private final boolean attachApplicationLocked(IApplicationThread thread,
6030            int pid) {
6031
6035        ProcessRecord app;
6036        if (pid != MY_PID && pid >= 0) {
6037            synchronized (mPidsSelfLocked) {
6038                app = mPidsSelfLocked.get(pid);
6039            }
6040        } else {
6041            app = null;
6042        }
6072        final String processName = app.processName;
6086        app.makeActive(thread, mProcessStats);
6087        app.curAdj = app.setAdj = -100;
6088        app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
6089        app.forcingToForeground = null;
6090        updateProcessForegroundLocked(app, false, false);
6091        app.hasShownUi = false;
6092        app.debugging = false;
6093        app.cached = false;
6096
6097        boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
6098        List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
6099
6107        try {
6152            ApplicationInfo appInfo = app.instrumentationInfo != null
6153                    ? app.instrumentationInfo : app.info;
6160            thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
6161                    profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
6162                    app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
6163                    isRestrictedBackupMode || !normalMode, app.persistent,
6164                    new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
6165                    mCoreSettingsObserver.getCoreSettingsLocked());
6166            updateLruProcessLocked(app, false, null);
6168        } catch (Exception e) {
6174            app.resetPackageList(mProcessStats);
6175            app.unlinkDeathRecipient();
6176            startProcessLocked(app, "bind fail", processName);
6177            return false;
6178        }
6179
6186        boolean badApp = false;
6187        boolean didSomething = false;
6188
6189        // See if the top visible activity is waiting to run in this process...
6190        if (normalMode) {
6191            try {
6192                if (mStackSupervisor.attachApplicationLocked(app)) {
6193                    didSomething = true;
6194                }
6195            } catch (Exception e) {
6197                badApp = true;
6198            }
6199        }
6200
6201        // Find any services that should be running in this process...
6202        if (!badApp) {
6203            try {
6204                didSomething |= mServices.attachApplicationLocked(app, processName);
6205            } catch (Exception e) {
6206                Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
6207                badApp = true;
6208            }
6209        }
6245
6246        return true;
6247    }
複製程式碼

第一步:呼叫了IApplicationThread的bindApplication

其中ApplicationInfo是在startProcessLocked是建立ProcessRecord時構建的,建立了一個AppBindData資料結構,並呼叫了
複製程式碼
739        public final void bindApplication(String processName, ApplicationInfo appInfo,
740                List<ProviderInfo> providers, ComponentName instrumentationName,
741                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
742                IInstrumentationWatcher instrumentationWatcher,
743                IUiAutomationConnection instrumentationUiConnection, int debugMode,
744                boolean enableOpenGlTrace, boolean isRestrictedBackupMode, boolean persistent,
745                Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services,
746                Bundle coreSettings) {
747
748            if (services != null) {
749                // 似乎就三個提前儲存的:package、window、alarm
750                ServiceManager.initServiceCache(services);
751            }
791
792            AppBindData data = new AppBindData();
793            data.processName = processName;
794            data.appInfo = appInfo;
795            data.providers = providers;
796            data.instrumentationName = instrumentationName;
797            data.instrumentationArgs = instrumentationArgs;
798            data.instrumentationWatcher = instrumentationWatcher;
799            data.instrumentationUiAutomationConnection = instrumentationUiConnection;
800            data.debugMode = debugMode;
801            data.enableOpenGlTrace = enableOpenGlTrace;
802            data.restrictedBackupMode = isRestrictedBackupMode;
803            data.persistent = persistent;
804            data.config = config;
805            data.compatInfo = compatInfo;
806            data.initProfilerInfo = profilerInfo;
807            sendMessage(H.BIND_APPLICATION, data);
808        }
複製程式碼

轉到主執行緒中處理handleBindApplication,構造了一個ContextIpl,

4254    private void handleBindApplication(AppBindData data) {
4255        mBoundApplication = data;
4256        mConfiguration = new Configuration(data.config);
4257        mCompatConfiguration = new Configuration(data.config);
4259        mProfiler = new Profiler();
4284
4289        if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
4290            AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
4291        }
4317        // 1.建立new LoadedApk(
4317        data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
4317        
4329        final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
4420        // 這裡加一個判斷還是很費解的,兩個分支邏輯基本一樣,所以任選一條分析
4421        if (data.instrumentationName != null) {
4422            InstrumentationInfo ii = null;
4423            try {
4424                ii = appContext.getPackageManager().
4425                    getInstrumentationInfo(data.instrumentationName, 0);
4426            } catch (PackageManager.NameNotFoundException e) {
4427            }
4442            ApplicationInfo instrApp = new ApplicationInfo();
4443            instrApp.packageName = ii.packageName;
4444            instrApp.sourceDir = ii.sourceDir;
4445            instrApp.publicSourceDir = ii.publicSourceDir;
4446            instrApp.splitSourceDirs = ii.splitSourceDirs;
4447            instrApp.splitPublicSourceDirs = ii.splitPublicSourceDirs;
4448            instrApp.dataDir = ii.dataDir;
4449            instrApp.nativeLibraryDir = ii.nativeLibraryDir;
4450            LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
4451                    appContext.getClassLoader(), false, true, false);
4452            ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
4453
4454            try {
4455                java.lang.ClassLoader cl = instrContext.getClassLoader();
4456                mInstrumentation = (Instrumentation)
4457                    cl.loadClass(data.instrumentationName.getClassName()).newInstance();
4458            } catch (Exception e) {
4462            }
4463
4464            mInstrumentation.init(this, instrContext, appContext,
4465                   new ComponentName(ii.packageName, ii.name), data.instrumentationWatcher,
4466                   data.instrumentationUiAutomationConnection);
4476        } else {
4476             // 2.建立new Instrumentation(
4477            mInstrumentation = new Instrumentation();
4478        }
4479
4488        try {
4488             // 3.建立了Application物件,並呼叫了attachBaseContext
4491            Application app = data.info.makeApplication(data.restrictedBackupMode, null);
4492            mInitialApplication = app;
4496            if (!data.restrictedBackupMode) {
4497                List<ProviderInfo> providers = data.providers;
4498                if (providers != null) {
4499             // 3.安裝程式中攜帶的Providers
4499                    installContentProviders(app, providers);
4502                    mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
4503                }
4504            }
4508            mInstrumentation.onCreate(data.instrumentationArgs); // 沒什麼用
4508             // 4.呼叫了application的onCreate操作
4518            mInstrumentation.callApplicationOnCreate(app);
4526        } finally {
4528        }
4529    }
4530
複製程式碼

這段程式碼裡面的分支條件有點頭暈,總之穿件了一個LoadedApk、Instrumentation、Application、ContextImpl。其中Application有LoadedApk.makeApplication構建的,最終由Instrmentation.newApplication構建,即呼叫了Application構造方法,並attach了ContextImpl,由此可見Application在attachBaseContext的時候輸入的是這裡的ContextImpl。這裡得注意一下,Provider的安裝是在Application的attachBaseContext和onCreate之間的。

LoadedApk

539    public Application makeApplication(boolean forceDefaultAppClass,
540            Instrumentation instrumentation) {
541        if (mApplication != null) {
542            return mApplication;
543        }
544
545        Application app = null;
547        String appClass = mApplicationInfo.className;
551
552        try {
553            java.lang.ClassLoader cl = getClassLoader();
557            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
558            app = mActivityThread.mInstrumentation.newApplication(
559                    cl, appClass, appContext);
560            appContext.setOuterContext(app);
561        } catch (Exception e) {
567        }
568        mActivityThread.mAllApplications.add(app);
569        mApplication = app;
594        }
595
596        return app;
597    }
複製程式碼

第二步:呼叫了mStackSupervisor.attachApplicationLocked(app)

ActivityStackSupervisor.attachApplicationLocked() 
ActivityStackSupervisor.realStartActivityLocked() 
IApplicationThread.scheduleLauncherActivity() 
ActivityThread.sendMessage() 
ActivityThread.H.sendMessage() 
ActivityThread.H.handleMessage() 
ActivityThread.handleLauncherActivity() 
ActivityThread.performLauncherActivity() 
Instrumentation.callActivityOnCreate() 
Activity.onCreate() 
ActivityThread.handleResumeActivity() 
ActivityThread.performResumeActivity() 
Activity.performResume() 
Instrumentation.callActivityOnResume() 
Activity.onResume() 
ActivityManagerNative.getDefault().activityResumed(token) 
複製程式碼
511    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
512        final String processName = app.processName;
513        boolean didSomething = false;
514        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
515            ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
516            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
517                final ActivityStack stack = stacks.get(stackNdx);
518                if (!isFrontStack(stack)) {
519                    continue;
520                }
521                ActivityRecord hr = stack.topRunningActivityLocked(null);
522                if (hr != null) {
523                    if (hr.app == null && app.uid == hr.info.applicationInfo.uid
524                            && processName.equals(hr.processName)) {
525                        try {
526                            if (realStartActivityLocked(hr, app, true, true)) {
527                                didSomething = true;
528                            }
529                        } catch (RemoteException e) {
532                            throw e;
533                        }
534                    }
535                }
536            }
537        }
538        if (!didSomething) {
539            ensureActivitiesVisibleLocked(null, 0);
540        }
541        return didSomething;
542    }
複製程式碼
1061    final boolean realStartActivityLocked(ActivityRecord r,
1062            ProcessRecord app, boolean andResume, boolean checkConfig)
1063            throws RemoteException {
1064
1084
1085        r.app = app;
1086        app.waitingToKill = null;
1087        r.launchCount++;
1088        r.lastLaunchTime = SystemClock.uptimeMillis();
1098
1099        final ActivityStack stack = r.task.stack;
1100        try {
1104            List<ResultInfo> results = null;
1105            List<Intent> newIntents = null;
1106            if (andResume) {
1107                results = r.results;
1108                newIntents = r.newIntents;
1109            }
1152
1156            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP);
1157            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1158                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
1159                    r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
1160                    results, newIntents, !andResume, mService.isNextTransitionForward(),
1161                    profilerInfo);
1162
1183        } catch (RemoteException e) {
1200        }
1235        return true;
1236    }
複製程式碼
2343    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
2348
2360        Activity a = performLaunchActivity(r, customIntent);
2361
2362        if (a != null) {
2363            r.createdConfig = new Configuration(mConfiguration);
2364            Bundle oldState = r.state;
2365            handleResumeActivity(r.token, false, r.isForward,
2366                    !r.activity.mFinished && !r.startsNotResumed);
2367
2368            if (!r.activity.mFinished && r.startsNotResumed) {
2378                try {
2379                    r.activity.mCalled = false;
2380                    mInstrumentation.callActivityOnPause(r.activity);
2388                    if (r.isPreHoneycomb()) {
2389                        r.state = oldState;
2390                    }
2396
2397                } catch (SuperNotCalledException e) {
2398                    throw e;
2399
2400                } catch (Exception e) {
2407                }
2408                r.paused = true;
2409            }
2410        } else {
2419        }
2420    }
複製程式碼

首先呼叫了performLaunchActivity,而後呼叫了handleResumeActivity,分別看看這兩個關鍵函式吧:

2175    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
2177
2178        ActivityInfo aInfo = r.activityInfo;
2195
2196        Activity activity = null;
2197        try {
2198            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
2198            // 1.利用mIntrumentation建立了一個Activity
2199            activity = mInstrumentation.newActivity(
2200                    cl, component.getClassName(), r.intent);
2207        } catch (Exception e) {
2213        }
2214
2215        try {
2216            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
2225
2226            if (activity != null) {
2226            // 2.建立了一個ContextImpl並對Activity執行了attach操作
2227                Context appContext = createBaseContextForActivity(r, activity);
2232                activity.attach(appContext, this, getInstrumentation(), r.token,
2233                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
2234                        r.embeddedID, r.lastNonConfigurationInstances, config,
2235                        r.voiceInteractor);
2242                int theme = r.activityInfo.getThemeResource();
2243                if (theme != 0) {
2244                    activity.setTheme(theme);
2245                }
2246
2247                activity.mCalled = false;
2247            // 3.呼叫了Activity的onCreate操作
2248                if (r.isPersistable()) {
2249                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2250                } else {
2251                    mInstrumentation.callActivityOnCreate(activity, r.state);
2252                }
2258                r.activity = activity;
2260                if (!r.activity.mFinished) {
2260            // 3.呼叫了Activity的onStart操作
2261                    activity.performStart();
2262                    r.stopped = false;
2263                }
2264                if (!r.activity.mFinished) {
2265                    if (r.isPersistable()) {
2266                        if (r.state != null || r.persistentState != null) {
2267                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2268                                    r.persistentState);
2269                        }
2270                    } else if (r.state != null) {
2271                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2272                    }
2273                }
2288            }
2289            r.paused = true;
2290
2291            mActivities.put(r.token, r);
2292
2293        } catch (SuperNotCalledException e) {
2294            throw e;
2295
2296        } catch (Exception e) {
2302        }
2303
2304        return activity;
2305    }
複製程式碼

總結一下performLauncheActivity即是建立了一個Activity,執行了attach(ContextImpl),執行了onCreate操作、執行了onStart操作。

2974    final void handleResumeActivity(IBinder token,
2975            boolean clearHide, boolean isForward, boolean reallyResume) {
2982        // 1.呼叫了Activity的onResume操作
2982        ActivityClientRecord r = performResumeActivity(token, clearHide);
2983
2984        if (r != null) {
2985            final Activity a = r.activity;
2986
3031
3034            if (!r.activity.mFinished && willBeVisible
3035                    && r.activity.mDecor != null && !r.hideForNow) {
3058                r.activity.mVisibleFromServer = true;
3059                mNumVisibleActivities++;
3060                if (r.activity.mVisibleFromClient) {
3061                    r.activity.makeVisible();
3062                }
3063            }
3064
3065            if (!r.onlyLocalRequest) {
3066                r.nextIdle = mNewActivities;
3067                mNewActivities = r;
3067                // 2.前一個棧頂Activity的onPause操作
3070                Looper.myQueue().addIdleHandler(new Idler());
3071            }
3072            r.onlyLocalRequest = false;
3073
3075            if (reallyResume) {
3076                try {
3077                    // 3.通知一下Activity已經onResume了
3077                    ActivityManagerNative.getDefault().activityResumed(token);
3078                } catch (RemoteException ex) {
3079                }
3080            }
3082        } else {
3090        }
3091    }
複製程式碼

第三步:呼叫了mServices.attachApplicationLocked 與服務的啟動相關,這裡暫時不考慮了。

6.Activity執行的onStop流程

Looper.myQueue().addIdleHandler(new Idler()) 
Idler.queueIdle() 
ActivityManagerNative.getDefault().activityIdle() 
ActivityManagerService.activityIdle() 
ActivityStackSupervisor.activityIdleInternalLocked() 
ActivityStack.stopActivityLocked() 
IApplicationThread.scheduleStopActivity() 
ActivityThread.scheduleStopActivity() 
ActivityThread.sendMessage() 
ActivityThread.H.sendMessage() 
ActivityThread.H.handleMessage() 
ActivityThread.handleStopActivity() 
ActivityThread.performStopActivityInner() 
ActivityThread.callCallActivityOnSaveInstanceState() 
Instrumentation.callActivityOnSaveInstanceState() 
Activity.performSaveInstanceState() 
Activity.onSaveInstanceState() 
Activity.performStop() 
Instrumentation.callActivityOnStop() 
Activity.onStop() 
複製程式碼
3070                Looper.myQueue().addIdleHandler(new Idler());
複製程式碼
1525    private class Idler implements MessageQueue.IdleHandler {
1526        @Override
1527        public final boolean queueIdle() {
1528            ActivityClientRecord a = mNewActivities;
1529            boolean stopProfiling = false;
1530            if (mBoundApplication != null && mProfiler.profileFd != null
1531                    && mProfiler.autoStopProfiler) {
1532                stopProfiling = true;
1533            }
1534            if (a != null) {
1535                mNewActivities = null;
1536                IActivityManager am = ActivityManagerNative.getDefault();
1537                ActivityClientRecord prev;
1538                do {
1543                    if (a.activity != null && !a.activity.mFinished) {
1544                        try {
1545                            am.activityIdle(a.token, a.createdConfig, stopProfiling);
1546                            a.createdConfig = null;
1547                        } catch (RemoteException ex) {
1548                            // Ignore
1549                        }
1550                    }
1551                    prev = a;
1552                    a = a.nextIdle;
1553                    prev.nextIdle = null;
1554                } while (a != null);
1555            }
1560            return false;
1561        }
1562    }
複製程式碼
2214    final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout, Configuration config) {
2218        ArrayList<ActivityRecord> stops = null;
2219        ArrayList<ActivityRecord> finishes = null;
2220        ArrayList<UserStartedState> startingUsers = null;
2221        int NS = 0;
2222        int NF = 0;
2223        boolean booting = false;
2224        boolean enableScreen = false;
2225        boolean activityRemoved = false;
2226
2227        ActivityRecord r = ActivityRecord.forToken(token);
2228        if (r != null) {
2248            r.idle = true;
2249
2290        // Stop any activities that are scheduled to do so but have been
2291        // waiting for the next one to start.
2292        for (int i = 0; i < NS; i++) {
2293            r = stops.get(i);
2294            final ActivityStack stack = r.task.stack;
2295            if (r.finishing) {
2296                stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
2297            } else {
2298                stack.stopActivityLocked(r);
2299            }
2300        }
2338        return r;
2339    }
複製程式碼
2513    final void stopActivityLocked(ActivityRecord r) {
2530
2531        if (r.app != null && r.app.thread != null) {
2532            adjustFocusedActivityLocked(r);
2533            r.resumeKeyDispatchingLocked();
2534            try {
2535                r.stopped = false;
2541                if (!r.visible) {
2542                    mWindowManager.setAppVisibility(r.appToken, false);
2543                }
2544                r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
2550            } catch (Exception e) {
2562            }
2563        }
2564    }
複製程式碼
3385    private void handleStopActivity(IBinder token, boolean show, int configChanges) {
3386        ActivityClientRecord r = mActivities.get(token);
3387        r.activity.mConfigChangeFlags |= configChanges;
3388
3389        StopInfo info = new StopInfo();
3390        performStopActivityInner(r, info, show, true);
3397
3399        if (!r.isPreHoneycomb()) {
3400            QueuedWork.waitToFinish();
3401        }
3408        info.activity = r;
3409        info.state = r.state;
3410        info.persistentState = r.persistentState;
3411        mH.post(info);
3412        mSomeActivitiesChanged = true;
3413    }
複製程式碼
3298    private void performStopActivityInner(ActivityClientRecord r,
3299            StopInfo info, boolean keepShown, boolean saveState) {
3300        if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
3301        if (r != null) {
3331            // Next have the activity save its current state and managed dialogs...
3332            if (!r.activity.mFinished && saveState) {
3333                if (r.state == null) {
3334                    callCallActivityOnSaveInstanceState(r);
3335                }
3336            }
3337
3338            if (!keepShown) {
3339                try {
3340                    // Now we are idle.
3341                    r.activity.performStop();
3342                } catch (Exception e) {
3349                }
3350                r.stopped = true;
3351            }
3352
3353            r.paused = true;
3354        }
3355    }
複製程式碼

首先呼叫的onSaveInstanceState,其次呼叫了performStop操作,至此Activity的啟動的什麼週期都走完了。

7.啟動程式已存在的Activity

ActivityStackSupervisor

1238    void startSpecificActivityLocked(ActivityRecord r,
1239            boolean andResume, boolean checkConfig) {
1240        
1241        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1242                r.info.applicationInfo.uid, true);
1243
1244        r.task.stack.setLaunchTime(r);
1245        // 程式已經啟動了,且繫結了IApplicationThread
1246        if (app != null && app.thread != null) {
1247            try {
1248                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1249                        || !"android".equals(r.info.packageName)) {
1254                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1255                            mService.mProcessStats);
1256                }
1257                realStartActivityLocked(r, app, andResume, checkConfig);
1258                return;
1259            } catch (RemoteException e) {
1262            }
1266        }
1267        // 啟動一個新的程式了哈
1268        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1269                "activity", r.intent.getComponent(), false, false, true);
1270    }
複製程式碼

這是貼的前面的程式碼,如果程式已經啟動了,即ProcessRecord和IApplicationThread都存在,那麼就呼叫realStartActivityLocked直接啟動Activity了。

8.總結:

1.生命週期

原始Activity A -> onPause -> onStop

目標Activity B -> onCreate -> onStart -> onResume

2.應用的啟動過程

startActivity -> startActivityForReuslt -> execStartActivity -> ActivityManagerService.execStartActivity -> ... -> 建立一個ActivityRecord、建立應用程式,程式建立之後 -> ActivityThread啟動 -> bindApplication -> 繫結完成之後看是否需要啟動Activity -> handleLauncheActivity -> handleResumeActivity -> Looper.getQueue().addIdleHandler() -> handleStopActivity -> end

參考:《Android原始碼解析之-->Activity啟動流程》blog.csdn.net/qq_23547831…

相關文章