Android-startActivity启动App生命周期源码分析

以A-App打开B-App为例


A-App进程
1.startActivity(launchIntentForPackage);
2.Activity.startActivityForResult();
public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                @Nullable Bundle options) {
            if (mParent == null) {
                options = transferSpringboardActivityOptions(options);
                Instrumentation.ActivityResult ar =
                    mInstrumentation.execStartActivity(
                        this, mMainThread.getApplicationThread(), mToken, this,
                        intent, requestCode, options);
                if (ar != null) {
                    mMainThread.sendActivityResult(
                        mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                        ar.getResultData());
                }
                if (requestCode >= 0) {
                    // If this start is requesting a result, we can avoid making
                    // the activity visible until the result is received.  Setting
                    // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
                    // activity hidden during this time, to avoid flickering.
                    // This can only be done when a result is requested because
                    // that guarantees we will get information back when the
                    // activity is finished, no matter what happens to it.
                    mStartedActivity = true;
                }

                cancelInputsAndStartExitTransition(options);
                // TODO Consider clearing/flushing other event sources and events for child windows.
            } else {
                if (options != null) {
                    mParent.startActivityFromChild(this, intent, requestCode, options);
                } else {
                    // Note we want to go through this method for compatibility with
                    // existing applications that may have overridden it.
                    mParent.startActivityFromChild(this, intent, requestCode);
                }
            }
        }

}
3.Instrumentation.execStartActivity();
public class Instrumentation {

    public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
            IApplicationThread whoThread = (IApplicationThread) contextThread;
            Uri referrer = target != null ? target.onProvideReferrer() : null;
            if (referrer != null) {
                intent.putExtra(Intent.EXTRA_REFERRER, referrer);
            }
            if (mActivityMonitors != null) {
                synchronized (mSync) {
                    final int N = mActivityMonitors.size();
                    for (int i=0; i<N; i++) {
                        final ActivityMonitor am = mActivityMonitors.get(i);
                        ActivityResult result = null;
                        if (am.ignoreMatchingSpecificIntents()) {
                            result = am.onStartActivity(intent);
                        }
                        if (result != null) {
                            am.mHits++;
                            return result;
                        } else if (am.match(who, null, intent)) {
                            am.mHits++;
                            if (am.isBlocking()) {
                                return requestCode >= 0 ? am.getResult() : null;
                            }
                            break;
                        }
                    }
                }
            }
            try {
                intent.migrateExtraStreamToClipData();
                intent.prepareToLeaveProcess(who);
                int result = ActivityTaskManager.getService()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null,
                            requestCode, 0, null, options);
                checkStartActivityResult(result, intent);
            } catch (RemoteException e) {
                throw new RuntimeException("Failure from system", e);
            }
            return null;
        }

}
4.ActivityTaskManager.getService()
                      .startActivity(whoThread, who.getBasePackageName(), intent,
                              intent.resolveTypeIfNeeded(who.getContentResolver()),
                              token, target != null ? target.mEmbeddedID : null,
                              requestCode, 0, null, options);

SystemServer进程
5.ActivityTaskManagerService.startActivityAsUser();
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

        @Override
        public final int startActivity(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags, profilerInfo, bOptions,
                    UserHandle.getCallingUserId());
        }

        int startActivityAsUser(IApplicationThread caller, String callingPackage,
                    Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                    int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
                    boolean validateIncomingUser) {
                enforceNotIsolatedCaller("startActivityAsUser");

                userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                        Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

                // TODO: Switch to user app stacks here.
                return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                        .setCaller(caller)
                        .setCallingPackage(callingPackage)
                        .setResolvedType(resolvedType)
                        .setResultTo(resultTo)
                        .setResultWho(resultWho)
                        .setRequestCode(requestCode)
                        .setStartFlags(startFlags)
                        .setProfilerInfo(profilerInfo)
                        .setActivityOptions(bOptions)
                        .setMayWait(userId)
                        .execute();

            }

}
6.ActivityStarter.startActivityMayWait()
class ActivityStarter {

    int execute() {
            try {
                // TODO(b/64750076): Look into passing request directly to these methods to allow
                // for transactional diffs and preprocessing.
                if (mRequest.mayWait) {
                    return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                            mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                            mRequest.intent, mRequest.resolvedType,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                            mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                            mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                            mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup,
                            mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
                } else {
                    return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                            mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                            mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                            mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                            mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                            mRequest.outActivity, mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup,
                            mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
                }
            } finally {
                onExecutionComplete();
            }
        }

}
中间调用栈太多了,有些就不贴具体源码了
7.ActivityStarter.startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
              String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
              IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
              String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
              SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
              ActivityRecord[] outActivity, TaskRecord inTask, String reason,
              boolean allowPendingRemoteAnimationRegistryLookup,
              PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart)
8.ActivityStarter.startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                  IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                  int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                  ActivityRecord[] outActivity, boolean restrictedBgActivity)
9.ActivityStarter.startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
              int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
              ActivityRecord[] outActivity, boolean restrictedBgActivity)
10.RootActivityContainer.resumeFocusedStacksTopActivities(
               ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions)
11.ActivityStack.resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options)
12.ActivityStack.resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options)
13.ActivityDisplay.pauseBackStacks(boolean userLeaving, ActivityRecord resuming, boolean dontWait);
14.ActivityStack.startPausingLocked(boolean userLeaving, boolean uiSleeping,
               ActivityRecord resuming, boolean pauseImmediately)
15.ClientLifecycleManager.scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
               @NonNull ActivityLifecycleItem stateRequest)
class ClientLifecycleManager {
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            final IApplicationThread client = transaction.getClient();
            transaction.schedule();
            if (!(client instanceof Binder)) {
                // If client is not an instance of Binder - it's a remote call and at this point it is
                // safe to recycle the object. All objects used for local calls will be recycled after
                // the transaction is executed on client in ActivityThread.
                transaction.recycle();
            }
        }
}
public class ClientTransaction implements Parcelable, ObjectPoolItem {
    public void schedule() throws RemoteException {
            mClient.scheduleTransaction(this);
        }
}
这里的mClient其实是4.方法中传入的whoThread对象代理(ApplicationThread对象)

A-App进程
16.ActivityThread.this.scheduleTransaction(transaction);
这里收到的transaction携带了PauseActivityItem对象(14.方法内部调用的mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
                                                   prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
                                                           prev.configChangeFlags, pauseImmediately));)
private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
}
ActivityThread父类是ClientTransactionHandler
public abstract class ClientTransactionHandler {
    void scheduleTransaction(ClientTransaction transaction) {
            transaction.preExecute(this);
            sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
        }
}
17.TransactionExecutor.execute(ClientTransaction transaction)
class H extends Handler {
    public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
            case EXECUTE_TRANSACTION:
                 final ClientTransaction transaction = (ClientTransaction) msg.obj;
                 mTransactionExecutor.execute(transaction);
                 if (isSystem()) {
                     // Client transactions inside system process are recycled on the client side
                     // instead of ClientLifecycleManager to avoid being cleared before this
                     // message is handled.
                     transaction.recycle();
                 }
                 // TODO(lifecycler): Recycle locally scheduled transactions.
                 break;
    }
}
public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");

            final IBinder token = transaction.getActivityToken();
            if (token != null) {
                final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
                        mTransactionHandler.getActivitiesToBeDestroyed();
                final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
                if (destroyItem != null) {
                    if (transaction.getLifecycleStateRequest() == destroyItem) {
                        // It is going to execute the transaction that will destroy activity with the
                        // token, so the corresponding to-be-destroyed record can be removed.
                        activitiesToBeDestroyed.remove(token);
                    }
                    if (mTransactionHandler.getActivityClient(token) == null) {
                        // The activity has not been created but has been requested to destroy, so all
                        // transactions for the token are just like being cancelled.
                        Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
                                + transactionToString(transaction, mTransactionHandler));
                        return;
                    }
                }
            }

            if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));

            executeCallbacks(transaction);

            executeLifecycleState(transaction);
            mPendingActions.clear();
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
        }
}
18.TransactionExecutor.executeLifecycleState(ClientTransaction transaction)
19.ActivityLifecycleItem.execute(mTransactionHandler, token, mPendingActions);
   ActivityLifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
public class PauseActivityItem extends ActivityLifecycleItem {
    public void execute(ClientTransactionHandler client, IBinder token,
                PendingTransactionActions pendingActions) {
            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
            client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                    "PAUSE_ACTIVITY_ITEM");
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
}
public final class ActivityThread extends ClientTransactionHandler {
    @Override
    public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
            int configChanges, PendingTransactionActions pendingActions, String reason) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            if (userLeaving) {
                performUserLeavingActivity(r);
            }

            r.activity.mConfigChangeFlags |= configChanges;
            performPauseActivity(r, finished, reason, pendingActions);

            // Make sure any pending writes are now committed.
            if (r.isPreHoneycomb()) {
                QueuedWork.waitToFinish();
            }
            mSomeActivitiesChanged = true;
        }
    }
}
20.ActivityThread.performPauseActivity(r, finished, reason, pendingActions);
21.ActivityThread.performPauseActivityIfNeeded(ActivityClientRecord r, String reason)
22.Instrumentation.callActivityOnPause(Activity activity)
23.Activity.performPause()
24.Activity.onPause() ------------------------------------>Activity回调
此时A-App的Activity生命周期中的onPause方法就会回调

SystemServer进程
25.ActivityTaskManagerService.activityPaused()《由19.ActivityLifecycleItem.postExecute(PauseActivityItem)调用而来》
public class PauseActivityItem extends ActivityLifecycleItem {
    @Override
    public void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        if (mDontReport) {
            return;
        }
        try {
            // TODO(lifecycler): Use interface callback instead of AMS.
            ActivityTaskManager.getService().activityPaused(token);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
}
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    @Override
    public final void activityPaused(IBinder token) {
        final long origId = Binder.clearCallingIdentity();
        synchronized (mGlobalLock) {
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            if (stack != null) {
                stack.activityPausedLocked(token, false);
            }
        }
        Binder.restoreCallingIdentity(origId);
    }
}
26.ActivityStack.activityPausedLocked(IBinder token, boolean timeout)
class ActivityStack extends ConfigurationContainer {
    private class ActivityStackHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case PAUSE_TIMEOUT_MSG: {
                        ActivityRecord r = (ActivityRecord)msg.obj;
                        // We don't at this point know if the activity is fullscreen,
                        // so we need to be conservative and assume it isn't.
                        Slog.w(TAG, "Activity pause timeout for " + r);
                        synchronized (mService.mGlobalLock) {
                            if (r.hasProcess()) {
                                mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r);
                            }
                            activityPausedLocked(r.appToken, true);
                        }
                    } break;
                }
            }
    }
}
27.ActivityStack.completePauseLocked(boolean resumeNext, ActivityRecord resuming)
28.RootActivityContainer.resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions)
29.ActivityStack.resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options)
30.ActivityStack.resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options)
31.ActivityStackSupervisor.startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig)
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
    void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
            // Is this activity's application already running?
            final WindowProcessController wpc =
                    mService.getProcessController(r.processName, r.info.applicationInfo.uid);

            boolean knownToBeDead = false;
            if (wpc != null && wpc.hasThread()) {
                try {
                    realStartActivityLocked(r, wpc, andResume, checkConfig);
                    return;
                } catch (RemoteException e) {
                    Slog.w(TAG, "Exception when starting activity "
                            + r.intent.getComponent().flattenToShortString(), e);
                }

                // If a dead object exception was thrown -- fall through to
                // restart the application.
                knownToBeDead = true;
            }

            // Suppress transition until the new activity becomes ready, otherwise the keyguard can
            // appear for a short amount of time before the new process with the new activity had the
            // ability to set its showWhenLocked flags.
            if (getKeyguardController().isKeyguardLocked()) {
                r.notifyUnknownVisibilityLaunched();
            }

            try {
                if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
                    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
                            + r.processName);
                }
                // Post message to start process to avoid possible deadlock of calling into AMS with the
                // ATMS lock held.
                final Message msg = PooledLambda.obtainMessage(
                        ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                        r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
                mService.mH.sendMessage(msg);
            } finally {
                Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
            }
        }
}
32.ActivityTaskManagerService.mH.sendMessage(msg);
33.ActivityManagerService.startProcessLocked(String processName,
               ApplicationInfo info, boolean knownToBeDead, int intentFlags,
               HostingRecord hostingRecord, boolean allowWhileBooting,
               boolean isolated, boolean keepIfLarge)
public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    public final class LocalService extends ActivityManagerInternal {
        @Override
        public void startProcess(String processName, ApplicationInfo info,
                boolean knownToBeDead, String hostingType, ComponentName hostingName) {
            try {
                if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
                            + processName);
                }
                synchronized (ActivityManagerService.this) {
                    startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                            new HostingRecord(hostingType, hostingName),
                            false /* allowWhileBooting */, false /* isolated */,
                            true /* keepIfLarge */);
                }
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
        }
    }
}
中间的调用过程省略,最终会调用到34
34.Process.start()
public class Process {
    public static ProcessStartResult start(@NonNull final String processClass,
                                               @Nullable final String niceName,
                                               int uid, int gid, @Nullable int[] gids,
                                               int runtimeFlags,
                                               int mountExternal,
                                               int targetSdkVersion,
                                               @Nullable String seInfo,
                                               @NonNull String abi,
                                               @Nullable String instructionSet,
                                               @Nullable String appDataDir,
                                               @Nullable String invokeWith,
                                               @Nullable String packageName,
                                               @Nullable String[] zygoteArgs) {
            return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                        runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                        abi, instructionSet, appDataDir, invokeWith, packageName,
                        /*useUsapPool=*/ true, zygoteArgs);
        }
}
35.ZygoteProcess.start(@NonNull final String processClass,
                                                     final String niceName,
                                                     int uid, int gid, @Nullable int[] gids,
                                                     int runtimeFlags, int mountExternal,
                                                     int targetSdkVersion,
                                                     @Nullable String seInfo,
                                                     @NonNull String abi,
                                                     @Nullable String instructionSet,
                                                     @Nullable String appDataDir,
                                                     @Nullable String invokeWith,
                                                     @Nullable String packageName,
                                                     boolean useUsapPool,
                                                     @Nullable String[] zygoteArgs)
36.ZygoteProcess.startViaZygote(@NonNull final String processClass,
                                                         @Nullable final String niceName,
                                                         final int uid, final int gid,
                                                         @Nullable final int[] gids,
                                                         int runtimeFlags, int mountExternal,
                                                         int targetSdkVersion,
                                                         @Nullable String seInfo,
                                                         @NonNull String abi,
                                                         @Nullable String instructionSet,
                                                         @Nullable String appDataDir,
                                                         @Nullable String invokeWith,
                                                         boolean startChildZygote,
                                                         @Nullable String packageName,
                                                         boolean useUsapPool,
                                                         @Nullable String[] extraArgs)
37.ZygoteProcess.attemptZygoteSendArgsAndGetResult(
                   ZygoteState zygoteState, String msgStr)
public class ZygoteProcess {
    private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
                ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
            try {
                final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
                final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;

                zygoteWriter.write(msgStr);
                zygoteWriter.flush();

                // Always read the entire result from the input stream to avoid leaving
                // bytes in the stream for future process starts to accidentally stumble
                // upon.
                Process.ProcessStartResult result = new Process.ProcessStartResult();
                result.pid = zygoteInputStream.readInt();
                result.usingWrapper = zygoteInputStream.readBoolean();

                if (result.pid < 0) {
                    throw new ZygoteStartFailedEx("fork() failed");
                }

                return result;
            } catch (IOException ex) {
                zygoteState.close();
                Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
                        + ex.toString());
                throw new ZygoteStartFailedEx(ex);
            }
        }
}
38.zygoteWriter.write(msgStr); 这里是通过LocalSocket LocalServerSocket和zygote进程通信,让zygote进程帮忙分裂一个新的app进程

Zygote进程
39.ZygoteInit.main()
public class ZygoteInit {
        public static void main(String argv[]) {
            ZygoteServer zygoteServer = null;

            // Mark zygote start. This ensures that thread creation will throw
            // an error.
            ZygoteHooks.startZygoteNoThreadCreation();

            // Zygote goes into its own process group.
            try {
                Os.setpgid(0, 0);
            } catch (ErrnoException ex) {
                throw new RuntimeException("Failed to setpgid(0,0)", ex);
            }

            Runnable caller;
            try {
                // Report Zygote start time to tron unless it is a runtime restart
                if (!"1".equals(SystemProperties.get("sys.boot_completed"))) {
                    MetricsLogger.histogram(null, "boot_zygote_init",
                            (int) SystemClock.elapsedRealtime());
                }

                String bootTimeTag = Process.is64Bit() ? "Zygote64Timing" : "Zygote32Timing";
                TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag,
                        Trace.TRACE_TAG_DALVIK);
                bootTimingsTraceLog.traceBegin("ZygoteInit");
                RuntimeInit.enableDdms();

                boolean startSystemServer = false;
                String zygoteSocketName = "zygote";
                String abiList = null;
                boolean enableLazyPreload = false;
                for (int i = 1; i < argv.length; i++) {
                    if ("start-system-server".equals(argv[i])) {
                        startSystemServer = true;
                    } else if ("--enable-lazy-preload".equals(argv[i])) {
                        enableLazyPreload = true;
                    } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                        abiList = argv[i].substring(ABI_LIST_ARG.length());
                    } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                        zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
                    } else {
                        throw new RuntimeException("Unknown command line argument: " + argv[i]);
                    }
                }

                final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);

                if (abiList == null) {
                    throw new RuntimeException("No ABI list supplied.");
                }

                // In some configurations, we avoid preloading resources and classes eagerly.
                // In such cases, we will preload things prior to our first fork.
                if (!enableLazyPreload) {
                    bootTimingsTraceLog.traceBegin("ZygotePreload");
                    EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                            SystemClock.uptimeMillis());
                    preload(bootTimingsTraceLog);
                    EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                            SystemClock.uptimeMillis());
                    bootTimingsTraceLog.traceEnd(); // ZygotePreload
                } else {
                    Zygote.resetNicePriority();
                }

                // Do an initial gc to clean up after startup
                bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
                gcAndFinalize();
                bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC

                bootTimingsTraceLog.traceEnd(); // ZygoteInit
                // Disable tracing so that forked processes do not inherit stale tracing tags from
                // Zygote.
                Trace.setTracingEnabled(false, 0);


                Zygote.initNativeState(isPrimaryZygote);

                ZygoteHooks.stopZygoteNoThreadCreation();

                zygoteServer = new ZygoteServer(isPrimaryZygote);

                if (startSystemServer) {
                    Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

                    // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
                    // child (system_server) process.
                    if (r != null) {
                        r.run();
                        return;
                    }
                }

                Log.i(TAG, "Accepting command socket connections");

                // The select loop returns early in the child process after a fork and
                // loops forever in the zygote.
                caller = zygoteServer.runSelectLoop(abiList);
            } catch (Throwable ex) {
                Log.e(TAG, "System zygote died with exception", ex);
                throw ex;
            } finally {
                if (zygoteServer != null) {
                    zygoteServer.closeServerSocket();
                }
            }

            // We're in the child process and have exited the select loop. Proceed to execute the
            // command.
            if (caller != null) {
                caller.run();
            }
        }
}
40.ZygoteServer.runSelectLoop(String abiList)
41.ZygoteConnection.processOneCommand(ZygoteServer zygoteServer)
class ZygoteConnection {
    Runnable processOneCommand(ZygoteServer zygoteServer) {
        String args[];
        ZygoteArguments parsedArgs = null;
        FileDescriptor[] descriptors;

        try {
            args = Zygote.readArgumentList(mSocketReader);

            // TODO (chriswailes): Remove this and add an assert.
            descriptors = mSocket.getAncillaryFileDescriptors();
        } catch (IOException ex) {
            throw new IllegalStateException("IOException on command socket", ex);
        }

        // readArgumentList returns null only when it has reached EOF with no available
        // data to read. This will only happen when the remote socket has disconnected.
        if (args == null) {
            isEof = true;
            return null;
        }

        int pid = -1;
        FileDescriptor childPipeFd = null;
        FileDescriptor serverPipeFd = null;

        parsedArgs = new ZygoteArguments(args);

        if (parsedArgs.mAbiListQuery) {
            handleAbiListQuery();
            return null;
        }

        if (parsedArgs.mPidQuery) {
            handlePidQuery();
            return null;
        }

        if (parsedArgs.mUsapPoolStatusSpecified) {
            return handleUsapPoolStatusChange(zygoteServer, parsedArgs.mUsapPoolEnabled);
        }

        if (parsedArgs.mPreloadDefault) {
            handlePreload();
            return null;
        }

        if (parsedArgs.mPreloadPackage != null) {
            handlePreloadPackage(parsedArgs.mPreloadPackage, parsedArgs.mPreloadPackageLibs,
                    parsedArgs.mPreloadPackageLibFileName, parsedArgs.mPreloadPackageCacheKey);
            return null;
        }

        if (canPreloadApp() && parsedArgs.mPreloadApp != null) {
            byte[] rawParcelData = Base64.getDecoder().decode(parsedArgs.mPreloadApp);
            Parcel appInfoParcel = Parcel.obtain();
            appInfoParcel.unmarshall(rawParcelData, 0, rawParcelData.length);
            appInfoParcel.setDataPosition(0);
            ApplicationInfo appInfo = ApplicationInfo.CREATOR.createFromParcel(appInfoParcel);
            appInfoParcel.recycle();
            if (appInfo != null) {
                handlePreloadApp(appInfo);
            } else {
                throw new IllegalArgumentException("Failed to deserialize --preload-app");
            }
            return null;
        }

        if (parsedArgs.mApiBlacklistExemptions != null) {
            return handleApiBlacklistExemptions(zygoteServer, parsedArgs.mApiBlacklistExemptions);
        }

        if (parsedArgs.mHiddenApiAccessLogSampleRate != -1
                || parsedArgs.mHiddenApiAccessStatslogSampleRate != -1) {
            return handleHiddenApiAccessLogSampleRate(zygoteServer,
                    parsedArgs.mHiddenApiAccessLogSampleRate,
                    parsedArgs.mHiddenApiAccessStatslogSampleRate);
        }

        if (parsedArgs.mPermittedCapabilities != 0 || parsedArgs.mEffectiveCapabilities != 0) {
            throw new ZygoteSecurityException("Client may not specify capabilities: "
                    + "permitted=0x" + Long.toHexString(parsedArgs.mPermittedCapabilities)
                    + ", effective=0x" + Long.toHexString(parsedArgs.mEffectiveCapabilities));
        }

        Zygote.applyUidSecurityPolicy(parsedArgs, peer);
        Zygote.applyInvokeWithSecurityPolicy(parsedArgs, peer);

        Zygote.applyDebuggerSystemProperty(parsedArgs);
        Zygote.applyInvokeWithSystemProperty(parsedArgs);

        int[][] rlimits = null;

        if (parsedArgs.mRLimits != null) {
            rlimits = parsedArgs.mRLimits.toArray(Zygote.INT_ARRAY_2D);
        }

        int[] fdsToIgnore = null;

        if (parsedArgs.mInvokeWith != null) {
            try {
                FileDescriptor[] pipeFds = Os.pipe2(O_CLOEXEC);
                childPipeFd = pipeFds[1];
                serverPipeFd = pipeFds[0];
                Os.fcntlInt(childPipeFd, F_SETFD, 0);
                fdsToIgnore = new int[]{childPipeFd.getInt$(), serverPipeFd.getInt$()};
            } catch (ErrnoException errnoEx) {
                throw new IllegalStateException("Unable to set up pipe for invoke-with", errnoEx);
            }
        }

        /**
         * In order to avoid leaking descriptors to the Zygote child,
         * the native code must close the two Zygote socket descriptors
         * in the child process before it switches from Zygote-root to
         * the UID and privileges of the application being launched.
         *
         * In order to avoid "bad file descriptor" errors when the
         * two LocalSocket objects are closed, the Posix file
         * descriptors are released via a dup2() call which closes
         * the socket and substitutes an open descriptor to /dev/null.
         */

        int [] fdsToClose = { -1, -1 };

        FileDescriptor fd = mSocket.getFileDescriptor();

        if (fd != null) {
            fdsToClose[0] = fd.getInt$();
        }

        fd = zygoteServer.getZygoteSocketFileDescriptor();

        if (fd != null) {
            fdsToClose[1] = fd.getInt$();
        }

        fd = null;

        pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
                parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
                parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
                parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);

        try {
            if (pid == 0) {
                // in child
                zygoteServer.setForkChild();

                zygoteServer.closeServerSocket();
                IoUtils.closeQuietly(serverPipeFd);
                serverPipeFd = null;

                return handleChildProc(parsedArgs, descriptors, childPipeFd,
                        parsedArgs.mStartChildZygote);
            } else {
                // In the parent. A pid < 0 indicates a failure and will be handled in
                // handleParentProc.
                IoUtils.closeQuietly(childPipeFd);
                childPipeFd = null;
                handleParentProc(pid, descriptors, serverPipeFd);
                return null;
            }
        } finally {
            IoUtils.closeQuietly(childPipeFd);
            IoUtils.closeQuietly(serverPipeFd);
        }
    }
}
42.Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
                   parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
                   parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
                   parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion)
c原生方法内部会执行到fork()函数,此时就会基于zygote进程分裂出一个新的app进程
app进程执行到if (pid == 0) 这里通常是0(子进程执行到这返回的一般为0),然后退出循环,执行caller.run();
zygote进程执行到if (pid == 0)通常大于0(子进程进程号),zygote进程runSelectLoop方法会继续循环,监听其他消息请求。

B-App进程(新app进程)
43.RuntimeInit.MethodAndArgsCaller.run()
static class MethodAndArgsCaller implements Runnable {
        /** method to call */
        private final Method mMethod;

        /** argument array */
        private final String[] mArgs;

        public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }

        public void run() {
            try {
                mMethod.invoke(null, new Object[] { mArgs });
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof Error) {
                    throw (Error) cause;
                }
                throw new RuntimeException(ex);
            }
        }
    }
44.ActivityThread.main()(被反射执行,一个App java世界的入口)
public final class ActivityThread extends ClientTransactionHandler {
        public static void main(String[] args) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

            // Install selective syscall interception
            AndroidOs.install();

            // CloseGuard defaults to true and can be quite spammy.  We
            // disable it here, but selectively enable it later (via
            // StrictMode) on debug builds, but using DropBox, not logs.
            CloseGuard.setEnabled(false);

            Environment.initForCurrentUser();

            // Make sure TrustedCertificateStore looks in the right place for CA certificates
            final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
            TrustedCertificateStore.setDefaultUserDirectory(configDir);

            Process.setArgV0("<pre-initialized>");

            Looper.prepareMainLooper();

            // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
            // It will be in the format "seq=114"
            long startSeq = 0;
            if (args != null) {
                for (int i = args.length - 1; i >= 0; --i) {
                    if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                        startSeq = Long.parseLong(
                                args[i].substring(PROC_START_SEQ_IDENT.length()));
                    }
                }
            }
            ActivityThread thread = new ActivityThread();
            thread.attach(false, startSeq);

            if (sMainThreadHandler == null) {
                sMainThreadHandler = thread.getHandler();
            }

            if (false) {
                Looper.myLooper().setMessageLogging(new
                        LogPrinter(Log.DEBUG, "ActivityThread"));
            }

            // End of event ActivityThreadMain.
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            Looper.loop();

            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
}
45.ActivityThread.attach(false, startSeq)
public final class ActivityThread extends ClientTransactionHandler {
    private void attach(boolean system, long startSeq) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            // Watch for getting close to heap limit.
            BinderInternal.addGcWatcher(new Runnable() {
                @Override public void run() {
                    if (!mSomeActivitiesChanged) {
                        return;
                    }
                    Runtime runtime = Runtime.getRuntime();
                    long dalvikMax = runtime.maxMemory();
                    long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                    if (dalvikUsed > ((3*dalvikMax)/4)) {
                        if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
                                + " total=" + (runtime.totalMemory()/1024)
                                + " used=" + (dalvikUsed/1024));
                        mSomeActivitiesChanged = false;
                        try {
                            ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
                        } catch (RemoteException e) {
                            throw e.rethrowFromSystemServer();
                        }
                    }
                }
            });
        } else {
            // Don't set application object here -- if the system crashes,
            // we can't display an alert, we just want to die die die.
            android.ddm.DdmHandleAppName.setAppName("system_process",
                    UserHandle.myUserId());
            try {
                mInstrumentation = new Instrumentation();
                mInstrumentation.basicInit(this);
                ContextImpl context = ContextImpl.createAppContext(
                        this, getSystemContext().mPackageInfo);
                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
        }

        ViewRootImpl.ConfigChangedCallback configChangedCallback
                = (Configuration globalConfig) -> {
            synchronized (mResourcesManager) {
                // We need to apply this change to the resources immediately, because upon returning
                // the view hierarchy will be informed about it.
                if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
                        null /* compat */)) {
                    updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                            mResourcesManager.getConfiguration().getLocales());

                    // This actually changed the resources! Tell everyone about it.
                    if (mPendingConfiguration == null
                            || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
                        mPendingConfiguration = globalConfig;
                        sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
                    }
                }
            }
        };
        ViewRootImpl.addConfigCallback(configChangedCallback);
    }
}

SystemServer进程
46.ActivityManagerService.attachApplication(IApplicationThread thread, long startSeq)

B-App进程
47.ApplicationThread.bindApplication()
public final class ActivityThread extends ClientTransactionHandler {
    private class ApplicationThread extends IApplicationThread.Stub {
        public final void bindApplication(String processName, ApplicationInfo appInfo,
                    List<ProviderInfo> providers, ComponentName instrumentationName,
                    ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                    IInstrumentationWatcher instrumentationWatcher,
                    IUiAutomationConnection instrumentationUiConnection, int debugMode,
                    boolean enableBinderTracking, boolean trackAllocation,
                    boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                    CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                    String buildSerial, AutofillOptions autofillOptions,
                    ContentCaptureOptions contentCaptureOptions) {
                if (services != null) {
                    if (false) {
                        // Test code to make sure the app could see the passed-in services.
                        for (Object oname : services.keySet()) {
                            if (services.get(oname) == null) {
                                continue; // AM just passed in a null service.
                            }
                            String name = (String) oname;

                            // See b/79378449 about the following exemption.
                            switch (name) {
                                case "package":
                                case Context.WINDOW_SERVICE:
                                    continue;
                            }

                            if (ServiceManager.getService(name) == null) {
                                Log.wtf(TAG, "Service " + name + " should be accessible by this app");
                            }
                        }
                    }

                    // Setup the service cache in the ServiceManager
                    ServiceManager.initServiceCache(services);
                }

                setCoreSettings(coreSettings);

                AppBindData data = new AppBindData();
                data.processName = processName;
                data.appInfo = appInfo;
                data.providers = providers;
                data.instrumentationName = instrumentationName;
                data.instrumentationArgs = instrumentationArgs;
                data.instrumentationWatcher = instrumentationWatcher;
                data.instrumentationUiAutomationConnection = instrumentationUiConnection;
                data.debugMode = debugMode;
                data.enableBinderTracking = enableBinderTracking;
                data.trackAllocation = trackAllocation;
                data.restrictedBackupMode = isRestrictedBackupMode;
                data.persistent = persistent;
                data.config = config;
                data.compatInfo = compatInfo;
                data.initProfilerInfo = profilerInfo;
                data.buildSerial = buildSerial;
                data.autofillOptions = autofillOptions;
                data.contentCaptureOptions = contentCaptureOptions;
                sendMessage(H.BIND_APPLICATION, data);
            }
    }
    class H extends Handler {
        public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
                    case BIND_APPLICATION:
                        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                        AppBindData data = (AppBindData)msg.obj;
                        handleBindApplication(data);
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        break;
                        }
        }
    }
}
48.Instrumentation.callApplicationOnCreate()
public class Instrumentation {
    public void callApplicationOnCreate(Application app) {
        app.onCreate();
    }
}
49.Application onCreate被执行

SystemServer进程
在执行bindApplication后,attachApplicationLocked后面还会执行其他方法
50.ActivityManagerService.attachApplicationLocked(IApplicationThread thread,int pid, int callingUid, long startSeq)
51.ActivityTaskManagerService.attachApplication(WindowProcessController wpc)
52.RootActivityContainer.attachApplication(WindowProcessController app)
53.ActivityStackSupervisor.realStartActivityLocked(ActivityRecord r, WindowProcessController proc,boolean andResume, boolean checkConfig)
54.ClientLifecycleManager.scheduleTransaction(ClientTransaction transaction)
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent)
clientTransaction.setLifecycleStateRequest(lifecycleItem);
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
class ClientLifecycleManager {
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        if (!(client instanceof Binder)) {
            // If client is not an instance of Binder - it's a remote call and at this point it is
            // safe to recycle the object. All objects used for local calls will be recycled after
            // the transaction is executed on client in ActivityThread.
            transaction.recycle();
        }
    }
}

B-App进程
55.ActivityThread.this.scheduleTransaction()
56.TransactionExecutor.execute(transaction)
public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction");

        final IBinder token = transaction.getActivityToken();
        if (token != null) {
            final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
                    mTransactionHandler.getActivitiesToBeDestroyed();
            final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
            if (destroyItem != null) {
                if (transaction.getLifecycleStateRequest() == destroyItem) {
                    // It is going to execute the transaction that will destroy activity with the
                    // token, so the corresponding to-be-destroyed record can be removed.
                    activitiesToBeDestroyed.remove(token);
                }
                if (mTransactionHandler.getActivityClient(token) == null) {
                    // The activity has not been created but has been requested to destroy, so all
                    // transactions for the token are just like being cancelled.
                    Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
                            + transactionToString(transaction, mTransactionHandler));
                    return;
                }
            }
        }

        if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }
}
57.TransactionExecutor.executeCallbacks(transaction)
58.LaunchActivityItem.execute()
public class LaunchActivityItem extends ClientTransactionItem {
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}
59.ActivityThread.handleLaunchActivity(ActivityClientRecord r,PendingTransactionActions pendingActions, Intent customIntent)
60.Instrumentation.callActivityOnCreate(Activity activity, Bundle icicle)
61.Acitvity.onCreate ------------------------------------>Activity回调
62.TransactionExecutor.executeLifecycleState(transaction)
63.TransactionExecutor.cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
64.TransactionExecutor.performLifecycleSequence(r, path, transaction)
65.ActivityThread.handleStartActivity(ActivityClientRecord r,PendingTransactionActions pendingActions)
66.Instrumentation.callActivityOnStart(Activity activity)
67.Acitvity.onStart ------------------------------------>Activity回调
68.lifecycleItem.execute(mTransactionHandler, token, mPendingActions)
public class ResumeActivityItem extends ActivityLifecycleItem {
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                "RESUME_ACTIVITY");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}
69.handleResumeActivity最终执行到Acitvity onResume回调
70.Looper.myQueue().addIdleHandler(new Idler());
public final class ActivityThread extends ClientTransactionHandler {
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                String reason) {
        Looper.myQueue().addIdleHandler(new Idler());
    }
}
71.am.activityIdle(a.token, a.createdConfig, stopProfiling)

SystemServer进程
72.ActivityTaskManagerService.activityIdle(IBinder token, Configuration config, boolean stopProfiling)
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    @Override
    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
        final long origId = Binder.clearCallingIdentity();
        try {
            WindowProcessController proc = null;
            synchronized (mGlobalLock) {
                ActivityStack stack = ActivityRecord.getStackLocked(token);
                if (stack == null) {
                    return;
                }
                final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
                        false /* fromTimeout */, false /* processPausingActivities */, config);
                if (r != null) {
                    proc = r.app;
                }
                if (stopProfiling && proc != null) {
                    proc.clearProfilerIfNeeded();
                }
            }
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }
}
73.ActivityStackSupervisor.activityIdleInternalLocked(final IBinder token, boolean fromTimeout,boolean processPausingActivities, Configuration config)
74.stack.stopActivityLocked(r);
75.ActivityStack.stopActivityLocked(ActivityRecord r)
mService.getLifecycleManager().scheduleTransaction(r.app.getThread(), r.appToken,
                        StopActivityItem.obtain(r.visible, r.configChangeFlags));
76.ClientLifecycleManager.scheduleTransaction(clientTransaction);

A-App进程
77.ActivityThread.this.scheduleTransaction()
private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }
}
78.ClientTransactionHandler.scheduleTransaction(ClientTransaction transaction)
public abstract class ClientTransactionHandler {
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
}
79.TransactionExecutor.execute(ClientTransaction transaction)
public final class ActivityThread extends ClientTransactionHandler {
    class H extends Handler {
        public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                switch (msg.what) {
                        case EXECUTE_TRANSACTION:
                        final ClientTransaction transaction = (ClientTransaction) msg.obj;
                        mTransactionExecutor.execute(transaction);
                        if (isSystem()) {
                            // Client transactions inside system process are recycled on the client side
                            // instead of ClientLifecycleManager to avoid being cleared before this
                            // message is handled.
                            transaction.recycle();
                        }
                        // TODO(lifecycler): Recycle locally scheduled transactions.
                        break;
                        }
        }
    }
}
80.mTransactionExecutor.execute(transaction);
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
81.StopActivityItem.execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions)
82.ActivityThread.handleStopActivity(IBinder token, boolean show, int configChanges,PendingTransactionActions pendingActions, boolean finalStateRequest, String reason)
83.ActivityThread.performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,boolean saveState, boolean finalStateRequest, String reason)
84.ActivityThread.callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason)
85.r.activity.performStop(r.mPreserveWindow, reason);
86.Instrumentation.callActivityOnStop(Activity activity)
87.Activity.onStop ------------------------------------>Activity回调

简单总结一下A-App进程打开B-App进程的过程

A-App进程(startActivity AMS服务)

->SystemServer进程,通知A-App进程执行onPause(ActivityThread.this.scheduleTransaction)
->A-App进程(Activity.onPause)
->SystemServer进程,通知Zygote进程创建B-App子进程(socket通信)
->Zygote进程 fork分裂出B-App进程
->B-App进程初始化时关联SystemServer进程(ActivityManagerService.attachApplication AMS服务)
->SystemServer进程通知B-App进程执行Application onCreate方法(ActivityThread.this.scheduleTransaction)
->SystemServer进程继续通知B-App进程执行Activity.onCreate Activity.onResume方法(ActivityThread.this.scheduleTransaction)
->B-App进程主线程队列空闲时通知SystemServer进程(ActivityTaskManagerService ATS服务)
->SystemServer进程通知A-App进程执行onStop(ActivityThread.this.scheduleTransaction)
->A-App进程(Activity.onStop)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345

推荐阅读更多精彩内容