Android学习-Activity启动流程

2025-06-23

从Laucher中启动Activity的流程

完整流程图

sequenceDiagram
    autonumber

    Actor User
    box User Process
    participant Laucher
    participant Activity
    participant Instrument
    participant ActivityManagerProxy
    end
    box ActivityManagerService
    participant ActivityManagerService
    participant ActivityStack
    participant ApplicationThreadProxy
    end
    box User Process
    participant ApplicationThread
    participant ActivityThread
    participant H
    end

    rect rgb(191, 223, 255)
    note right of User: try to start Specified Activity
    User->>+ Laucher: startActivitySafely
    Laucher->>+ Activity: startActivity
    Activity->>Activity: startActivityForResult
    Activity->>+Instrument: execStartActivity
    Instrument->>+ActivityManagerProxy: startActivity
    ActivityManagerProxy->>+ActivityManagerService: startActivity
    ActivityManagerService->>+ActivityStack: startActivityMayWait
    ActivityStack->>ActivityStack: startActivityLocked 
    ActivityStack->>ActivityStack:startActivityUncheckedLocked 
    ActivityStack->>ActivityStack: startActivityLocked 
    ActivityStack->>ActivityStack:  resumeTopActivityLocked
    end
    rect rgb(200, 150, 255)
    note right of Instrument: pause Launcher
    ActivityStack->>ActivityStack:  startPausingLocked
    ActivityStack->>+ApplicationThreadProxy:  schedulePauseActivity
    deactivate ActivityStack
    ApplicationThreadProxy->>+ApplicationThread: schedulePauseActivity
    ApplicationThread->>+ActivityThread:  queryOrSendMessage
    ActivityThread->>+ H: handleMessage
    H->>-ActivityThread:  handlePauseActivity
    ActivityThread->>Laucher:onUserLeavingHint
    ActivityThread->>Laucher:onPause
    deactivate Laucher
    deactivate Activity
    ActivityThread->>ActivityThread:QueuedWork.waitToFinish
    ActivityThread->>-ActivityManagerProxy:activityPaused
    ActivityManagerProxy->>ActivityManagerService:activityPaused
    ActivityManagerService->>+ActivityStack:  activityPaused
    end
    rect rgb(191, 223, 255)
    note right of Instrument: resume Specified Activity
    ActivityStack->>ActivityStack:completePauseLocked
    ActivityStack->>ActivityStack:resumeTopActivityLocked
    ActivityStack->>ActivityStack:startSepcificActivityLocked
    ActivityStack->>+ActivityManagerService:startProcessLocked
    deactivate ActivityStack
    ActivityManagerService->>ActivityManagerService:startProcessLocked
    ActivityManagerService->>+ActivityThread:main
    ActivityThread->>ActivityManagerProxy:attachApplication

    ActivityManagerProxy->>ActivityManagerService:attachApplication
    ActivityManagerService->>ActivityManagerService:attachApplicationLocked
    ActivityManagerService->>ActivityStack:realStartActivityLocked
    deactivate ActivityManagerService
    ActivityStack->>ApplicationThreadProxy:scheduleLaunchActivity
    ApplicationThreadProxy->>ApplicationThread:scheduleLaunchActivity
    ApplicationThread->>ActivityThread:queueOrSendMessage
    ActivityThread->>H:handleMessage
    H->>+ActivityThread:handleLaunchActivity
    ActivityThread->>ActivityThread:performLaunchActivity
    ActivityThread->>Activity: attach
    ActivityThread->>Activity:onCreate

    ActivityThread->>ActivityThread:Looper.loop
    deactivate ActivityThread
    end

详细步骤

step 1 执行LaucherstartActivitySafely方法,该方法调用了ActivitystartActivity方法

step 2 执行ActivitystartActivity方法:

    public void startActivity(Intent intent, @Nullable Bundle options) {
        ...
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            startActivityForResult(intent, -1);
        }
    }

,该方法调用了ActivitystartActivityForResult方法

step 3 执行startActivityForResult方法,Laucher不存在mParent,于是,执行下述语句

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            ...
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            ...
        } else {
            ...
        }
    }

ActivitymInstrumentation成员为Instrumentation类的一个对象,用于和Activity交互和监控Activity,这里调用了其execStartActivity方法

step 4 执行execStartActivity方法:

    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;
        ...
        try {
            ...
            int result = ActivityTaskManager.getDefault().startActivity(whoThread,
                    who.getOpPackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            notifyStartActivityResult(result, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

,方法通过ActivityManager.getService()方法获取到了ActivityMangerProxy的对象,

/**
 * class: ActivityTaskManager
 **/
public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

可以看出,返回了一个单例,实现了IActivityManager这个接口,用于与ActivityManagerService进行交互,并调用startActivity方法

step 5 执行startActivity方法:

      @Override public int startActivity(android.app.IApplicationThread caller, java.lang.String callingPackage, android.content.Intent intent, java.lang.String resolvedType, android.os.IBinder resultTo, java.lang.String resultWho, int requestCode, int flags, android.app.ProfilerInfo profilerInfo, android.os.Bundle options) throws android.os.RemoteException
      {
        android.os.Parcel _data = android.os.Parcel.obtain(asBinder());
        android.os.Parcel _reply = android.os.Parcel.obtain();
        int _result;
        try {
          _data.writeInterfaceToken(DESCRIPTOR);
          _data.writeStrongInterface(caller);
          _data.writeString(callingPackage);
          _data.writeTypedObject(intent, 0);
          _data.writeString(resolvedType);
          _data.writeStrongBinder(resultTo);
          _data.writeString(resultWho);
          _data.writeInt(requestCode);
          _data.writeInt(flags);
          _data.writeTypedObject(profilerInfo, 0);
          _data.writeTypedObject(options, 0);
          boolean _status = mRemote.transact(Stub.TRANSACTION_startActivity, _data, _reply, 0);
          _reply.readException();
          _result = _reply.readInt();
        }
        finally {
          _reply.recycle();
          _data.recycle();
        }
        return _result;
      }

,方法包装了一个Parcel并通过Binder发送给了IActivity$Stub,其code为Stub.TRANSACTION_startActivity,IActivity$Stub判断code的类型为Stub.TRANSACTION_startActivity,并执行:

public boolean onTransact(){
    ...
    switch (code)
      {
        ...
        case TRANSACTION_startActivity:
        {
          android.app.IApplicationThread _arg0;
          _arg0 = android.app.IApplicationThread.Stub.asInterface(data.readStrongBinder());
          java.lang.String _arg1;
          _arg1 = data.readString();
          android.content.Intent _arg2;
          _arg2 = data.readTypedObject(android.content.Intent.CREATOR);
          java.lang.String _arg3;
          _arg3 = data.readString();
          android.os.IBinder _arg4;
          _arg4 = data.readStrongBinder();
          java.lang.String _arg5;
          _arg5 = data.readString();
          int _arg6;
          _arg6 = data.readInt();
          int _arg7;
          _arg7 = data.readInt();
          android.app.ProfilerInfo _arg8;
          _arg8 = data.readTypedObject(android.app.ProfilerInfo.CREATOR);
          android.os.Bundle _arg9;
          _arg9 = data.readTypedObject(android.os.Bundle.CREATOR);
          data.enforceNoDataAvail();
          int _result = this.startActivity(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5, _arg6, _arg7, _arg8, _arg9);
          reply.writeNoException();
          reply.writeInt(_result);
          break;
        }
        ...
      }
    ...
}

,方法调用了StubstartActivity方法,该方法由ActivityManagerService重写ActivityManagerNative实现

public final class ActivityManagerService extends ActivityManagerNative

step 6 调用ActivityManagerServicestartActivity方法:

public final int startActivity(IApplicationThread caller,
        Intent intent, String resolvedType, Uri[] grantedUriPermissions,
        int grantedMode, IBinder resultTo,
        String resultWho, int requestCode, boolean onlyIfNeeded,
        boolean debug) {
    return mMainStack.startActivityMayWait(caller, intent, resolvedType,
            grantedUriPermissions, grantedMode, resultTo, resultWho,
            requestCode, onlyIfNeeded, debug, null, null);
}

,方法调用了mMainStackstartActivityMayWait方法。mMainStackActivityStack的实例,负责管理应用程序的Activity和任务栈

step 7 执行ActivityStack.startActivityMayWait方法:

final int startActivityMayWait(IApplicationThread caller,
        Intent intent, String resolvedType, Uri[] grantedUriPermissions,
        int grantedMode, IBinder resultTo,
        String resultWho, int requestCode, boolean onlyIfNeeded,
        boolean debug, WaitResult outResult, Configuration config) {
    // Refuse possible leaked file descriptors
    ...
    // Collect information about the target of the Intent.
    ...
    synchronized (mService) {
        ... 
        int res = startActivityLocked(caller, intent, resolvedType,
                grantedUriPermissions, grantedMode, aInfo,
                resultTo, resultWho, requestCode, callingPid, callingUid,
                onlyIfNeeded, componentSpecified);
        ...
    }
}

,调用了startActivityLocked方法

step 8 执行startActivityLocked方法:

    final int startActivityLocked(IApplicationThread caller,
            Intent intent, String resolvedType,
            Uri[] grantedUriPermissions,
            int grantedMode, ActivityInfo aInfo, IBinder resultTo,
            String resultWho, int requestCode,
            int callingPid, int callingUid, boolean onlyIfNeeded,
            boolean componentSpecified) {
        int err = START_SUCCESS;
        ProcessRecord callerApp = null;
        ...
        ActivityRecord sourceRecord = null;
        ActivityRecord resultRecord = null;
        ...      
        ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
                intent, resolvedType, aInfo, mService.mConfiguration,
                resultRecord, resultWho, requestCode, componentSpecified);
        ...
        return startActivityUncheckedLocked(r, sourceRecord,
                grantedUriPermissions, grantedMode, onlyIfNeeded, true);
    }
  

方法给要创建的Activity创建了一个ActivityRecord,并设置其sourceRecordLauncher,以此调用startActivityUncheckedLocked方法

step 9 执行startActivityUnchekedLocked方法:

final int startActivityUncheckedLocked(ActivityRecord r,
        ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
        int grantedMode, boolean onlyIfNeeded, boolean doResume) {
    ...
    boolean addingToTask = false;
    ...
    boolean newTask = false;
    if (r.resultTo == null && !addingToTask
            && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        mService.mCurTask++;
        if (mService.mCurTask <= 0) {
            mService.mCurTask = 1;
        }
        ...
        newTask = true;
        if (mMainStack) {
            mService.addRecentTaskLocked(r.task);
        }
        
    } 
    ...
    startActivityLocked(r, newTask, doResume);
    return START_SUCCESS;
}

对于要启动的Activity而言,newTask == true,然后调用重载的startActivityLocked方法

step 10 执行startActivityLocked方法:

    private final void startActivityLocked(ActivityRecord r, boolean newTask,
            boolean doResume) {
        final int NH = mHistory.size();
        int addPos = -1;
        ...
        if (addPos < 0) {
            addPos = NH;
        }
        ...
        mHistory.add(addPos, r);
        ...
        if (doResume) {
            resumeTopActivityLocked(null);
        }
    }

,由于启动新ActivitynewTask == true,于是将其ActivityRecord插入到栈的顶部,并执行resumeTopActivityLocked方法

step 11 执行resumeTopActivityLocked方法:

final boolean resumeTopActivityLocked(ActivityRecord prev) {
    ...
    final boolean userLeaving = mUserLeaving;
    mUserLeaving = false;
    ...
    // If the top activity is the resumed one, nothing to do.
    if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
        ...
        return false;
    }
    // If we are sleeping, and there is no resumed activity, and the top
    // activity is paused, well that is the state we want.
    if ((mService.mSleeping || mService.mShuttingDown)
            && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
        ...
        return false;
    }
    ...
    // If we are currently pausing an activity, then don't do anything
    // until that is done.
    if (mPausingActivity != null) {
        ...
        return false;
    }
    
    // We need to start pausing the current activity so the top one
    // can be resumed...
    if (mResumedActivity != null) {
        startPausingLocked(userLeaving, false);
        return true;
    }
    ...
}

,在方法中,判断当前的Activity是否resumed、是否正在休眠、是否正在停止一个Activity,如果都不是,则调用startPausingLocked方法停止正在运行的进程

step 12 执行startPausingLocked方法:

private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
    ActivityRecord prev = mResumedActivity;
    ...
    mResumedActivity = null;
    mPausingActivity = prev;
    ...
    mLastPausedActivity = prev;
    if (prev.app != null && prev.app.thread != null) {
        try {
            ...
            prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
                    prev.configChangeFlags);
            ...

        } catch (Exception e) {
            ...
        }
    } 
    ...
}

,调用了prev.app.thread.schedulePauseActivity方法,prev.app.thead为一个ApplicationThread$ApplicationThreadProxy类型的对象

step 13 执行schedulePauseActivity方法:

public final void schedulePauseActivity(IBinder token, boolean finished,
        boolean userLeaving, int configChanges) throws RemoteException {
    Parcel data = Parcel.obtain();
    data.writeInterfaceToken(IApplicationThread.descriptor);
    data.writeStrongBinder(token);
    data.writeInt(finished ? 1 : 0);
    data.writeInt(userLeaving ? 1 :0);
    data.writeInt(configChanges);
    mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
            IBinder.FLAG_ONEWAY);
    data.recycle();
}

,方法向远程服务发送了一个SCHEDULE_PAUSE_ACTIVITY_TRANSACTION的code,远程服务为ApplicationThreadNative类型的Stub,并实现了IApplicationThread接口:

public abstract class ApplicationThreadNative extends Binder implements IApplicationThread 

,当Stub接受到了请求后,执行onTransact方法:

public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
        throws RemoteException {
    switch (code) {
        case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IApplicationThread.descriptor);
            IBinder b = data.readStrongBinder();
            boolean finished = data.readInt() != 0;
            boolean userLeaving = data.readInt() != 0;
            int configChanges = data.readInt();
            schedulePauseActivity(b, finished, userLeaving, configChanges);
            return true;
        }
    }
}

,调用了schedulePauseActivity方法

step 14 执行schedulePauseActivity方法:

public final void schedulePauseActivity(IBinder token, boolean finished,
        boolean userLeaving, int configChanges) {
    queueOrSendMessage(
            finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
            token,
            (userLeaving ? 1 : 0),
            configChanges);
}

,该方法由ActivityThread$ApplicationThread中实现,调用queueOrSendMessage方法发送PAUSE_ACTIVITY的请求

step 15 执行queueOrSendMessage方法:

...
final H mH = new H();
...
private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
    synchronized (this) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        mH.sendMessage(msg);
    }
}

,向Handler发送了一条PAUSE_ACTIVITY的消息

step 16 执行sendMessage方法向mH发送一条消息,mH接收到消息后执行handleMessage方法:

public void handleMessage(Message msg) {
    ...
    switch (msg.what) {
        case PAUSE_ACTIVITY:
            handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
            maybeSnapshot();
            break;
        ...
    }
    ...
}

,调用了ActivityThreadhandlePauseActivity方法,Activity$H继承了Handler类:

private final class H extends Handler

step 17 执行handlePauseActivity方法:

private final void handlePauseActivity(IBinder token, boolean finished,
        boolean userLeaving, int configChanges) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        if (userLeaving) {
            performUserLeavingActivity(r);
        }
        Bundle state = performPauseActivity(token, finished, true);
        QueuedWork.waitToFinish();
        
        // Tell the activity manager we have paused.
        try {
            ActivityManagerNative.getDefault().activityPaused(token, state);
        } catch (RemoteException ex) {
        }
    }
}

,首先,调用performUserLeavingActivity方法,向Launcher发送userLeaving

step 18 执行performUserLeavingActivity方法:

final void performUserLeavingActivity(ActivityClientRecord r) {
    mInstrumentation.callActivityOnUserLeaving(r.activity);
}

,方法通过InstrumentationLaucher发送userLeaving,执行:

/**
 * class: Instrumentation
 **/
public void callActivityOnUserLeaving(Activity activity) {
    activity.performUserLeaving();
}

step 19 执行完performUserLeavingActivity后,执行performPauseActivity方法:

final Bundle performPauseActivity(IBinder token, boolean finished,
        boolean saveState) {
    ActivityClientRecord r = mActivities.get(token);
    return r != null ? performPauseActivity(r, finished, saveState) : null;
}
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
        boolean saveState) {
    ...
    try {
        ...
        r.activity.mCalled = false;
        mInstrumentation.callActivityOnPause(r.activity);
        ...
    }
    ...
    r.paused = true;
    return state;
}

,该方法设置Launcherr.mCalled = false,并调用了Instrumentation.callActivityOnPause方法,然后设置r.paused = true

public void callActivityOnPause(Activity activity) {
    activity.performPause();
}

step 20 执行QueuedWork.waitToFinish方法:

/**
 * Is called from the Activity base class's onPause(), after
 * BroadcastReceiver's onReceive, after Service command handling,
 **/
public static void waitToFinish() {
    Runnable toFinish;
    while ((toFinish = sPendingWorkFinishers.poll()) != null) {
        toFinish.run();
    }
}

,等待前面的任务完成执行

step 21step 17中,通过ActivityManagerNative.getDefault()获取到了ActivityManagerProxy对象,并调用其activityPaused方法向ActivityManagerService通知top Activity已经被pause了:

public void activityPaused(IBinder token, Bundle state) throws RemoteException
{
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    data.writeInterfaceToken(IActivityManager.descriptor);
    data.writeStrongBinder(token);
    data.writeBundle(state);
    mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
    reply.readException();
    data.recycle();
    reply.recycle();
}

,方法发送一个code为ACTIVITY_PAUSED_TRANSACTIONParcel

step 22 收到通信后,ActivityManagerService通过:

public boolean onTransact(){
    ...
    switch (code)
    {
        case ACTIVITY_PAUSED_TRANSACTION: {
            data.enforceInterface(IActivityManager.descriptor);
            IBinder token = data.readStrongBinder();
            Bundle map = data.readBundle();
            activityPaused(token, map);
            reply.writeNoException();
            return true;
        }
    }
    ...
}

调用activityPaused方法:

public final void activityPaused(IBinder token, Bundle icicle) {
    ...
    mMainStack.activityPaused(token, icicle, false);
    ...
}

,方法调用ActivityStackactivityPaused方法

step 23 执行ActivityStack.activityPaused方法:

final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {
    ...
    ActivityRecord r = null;
    synchronized (mService) {
        int index = indexOfTokenLocked(token);
        if (index >= 0) {
            r = (ActivityRecord)mHistory.get(index);
            ...
            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
            if (mPausingActivity == r) {
                r.state = ActivityState.PAUSED;
                completePauseLocked();
            }
            ...
        }
    }
}

,找到Laucher对应的ActivityRecord,在step 12中,语句mPausingActivity = prev设置了mPausingActivityLauncher,于是,设置LauncherActivityRecord.statePAUSED,并调用completePauseLocked方法

step 24 执行completePauseLocked方法:

private final void completePauseLocked() {
    ActivityRecord prev = mPausingActivity;
    if (prev != null) {
        ...
        mPausingActivity = null;
    }
    if (!mService.mSleeping && !mService.mShuttingDown) {
        resumeTopActivityLocked(prev);
    } 
    ...
    
}

,将mPausingActivity设置为null并再次调用resumeTopActivityLocked方法

step 25 执行resumeTopActivityLocked方法:

final boolean resumeTopActivityLocked(ActivityRecord prev) {
        ...
        if (next.app != null && next.app.thread != null){
            ...
        }
        else {
            ...
            startSpecificActivityLocked(next, true, true);
        }
        return true;
}

,此时,mResumedActivity == null, 于是调用startSpecificActivityLocked方法

step 26 执行startSpecificActivityLocked方法:

private final void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid);
    ...
    if (app != null && app.thread != null) {
        ...
    }
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false);
}

,此时,由于app == null && app.thread == null,于是继续执行mService.startProcessLocked方法,其中mService指向ActivityManagerService

step 27 ActivityManagerService执行startProcessLocked方法:

final ProcessRecord startProcessLocked(String processName,
        ApplicationInfo info, boolean knownToBeDead, int intentFlags,
        String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
    ProcessRecord app = getProcessRecordLocked(processName, info.uid);
    ...
    
    if (app == null) {
        app = newProcessRecordLocked(null, info, processName);
        mProcessNames.put(processName, info.uid, app);
    } 
    ...
    startProcessLocked(app, hostingType, hostingNameStr);
    return (app.pid != 0) ? app : null;
}

,创建一个ProcessRecord,并调用startProcessLocked方法运行该Process

step 28

private final void startProcessLocked(ProcessRecord app,
        String hostingType, String hostingNameStr) {
    ...
    try {
        ...
        int pid = Process.start("android.app.ActivityThread",
                mSimpleProcessManagement ? app.processName : null, uid, uid,
                gids, debugFlags, null);
        ...
    } 
    ...
}

,查看Process.start方法:

    public static final int start(final String processClass,
                                  final String niceName,
                                  int uid, int gid, int[] gids,
                                  int debugFlags,
                                  String[] zygoteArgs)
    {
        ...
        else {
            ...
            Runnable runnable = new Runnable() {
                        public void run() {
                            Process.invokeStaticMain(processClass);
                        }
            };
            
            if (niceName != null) {
                new Thread(runnable, niceName).start();
            } else {
                new Thread(runnable).start();
            }
            return 0;
        }
    }

,可以看到,其创建了一个线程,并运行invokeStaticMain方法:

private static void invokeStaticMain(String className) {
    Class cl;
    Object args[] = new Object[1];
    args[0] = new String[0];     //this is argv

    try {
        cl = Class.forName(className);
        cl.getMethod("main", new Class[] { String[].class })
                .invoke(null, args);            
    } 
    ...
}

,由于之前传入的processClass"android.app.ActivityThread",于是在此通过反向代理调用其静态main方法

step 29 执行main方法:

public static final void main(String[] args) {
    ...
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    ...
    Looper.loop();
    ...
}

,可以看到,创建了一个ActivityThread的实例,并调用了attach方法:

    private final void attach(boolean system) {
        sThreadLocal.set(this);
        mSystemThread = system;
        if (!system) {
            ...
            IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                ...
            }
        }      
        ...
    }

,方法调用了ActivityManagerProxyattachApplication方法,其中final ApplicationThread mAppThread = new ApplicationThread();在创建ActivityThread时创建

step 30 执行attachApplication方法,向ActivityManagerService发送ATTACH_APPLICATION_TRANSACTION请求:

public void attachApplication(IApplicationThread app) throws RemoteException
{
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    data.writeInterfaceToken(IActivityManager.descriptor);
    data.writeStrongBinder(app.asBinder());
    mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
    reply.readException();
    data.recycle();
    reply.recycle();
}

step 31 ActivityManagerService执行onTransact方法:

public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
        throws RemoteException {
    switch (code) {
        ...
        case ATTACH_APPLICATION_TRANSACTION: {
            data.enforceInterface(IActivityManager.descriptor);
            IApplicationThread app = ApplicationThreadNative.asInterface(
                    data.readStrongBinder());
            if (app != null) {
                attachApplication(app);
            }
            reply.writeNoException();
            return true;
        }
        ...
    }
    ...
}

,调用attachApplication方法:

public final void attachApplication(IApplicationThread thread) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        ...
        attachApplicationLocked(thread, callingPid);
        ...
    }
}

,调用attachApplicationLocked方法

step 32 执行attachApplicationLocked方法:

private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid) {
    // Find the application record that is being attached
    ProcessRecord app;
    ...
    app.thread = thread;
    ...
    mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
    ...
    ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
    if (hr != null && normalMode) {
        if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
                && processName.equals(hr.processName)) {
            try {
                if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                ...
            }
        } else {
            ...
        }
    }
}

,从Handler中移除PROC_START_TIMEOUT_MSG,并检查是否有Activity需要启动,于是调用ActivityStack.realStartActivityLocked方法

step 33 执行realStartActivityLocked方法:

final boolean realStartActivityLocked(ActivityRecord r,
        ProcessRecord app, boolean andResume, boolean checkConfig)
        throws RemoteException {
    ...
    try {
        ...
        app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
                System.identityHashCode(r),
                r.info, r.icicle, results, newIntents, !andResume,
                mService.isNextTransitionForward());
    }
    ...
    return true;
}

,调用了ApplicationThreadProxyscheduleLaunchActivity方法

step 34 执行scheduleLaunchActivity方法:

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
        ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
        List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
        throws RemoteException {
    Parcel data = Parcel.obtain();
    data.writeInterfaceToken(IApplicationThread.descriptor);
    intent.writeToParcel(data, 0);
    data.writeStrongBinder(token);
    data.writeInt(ident);
    info.writeToParcel(data, 0);
    data.writeBundle(state);
    data.writeTypedList(pendingResults);
    data.writeTypedList(pendingNewIntents);
    data.writeInt(notResumed ? 1 : 0);
    data.writeInt(isForward ? 1 : 0);
    mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
            IBinder.FLAG_ONEWAY);
    data.recycle();
}

,向ApplicationThread发送一个SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION类型的请求

step 35 ApplicationThread执行onTransact方法:

public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
        throws RemoteException {
    switch(code){
        case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IApplicationThread.descriptor);
            Intent intent = Intent.CREATOR.createFromParcel(data);
            IBinder b = data.readStrongBinder();
            int ident = data.readInt();
            ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data);
            Bundle state = data.readBundle();
            List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR);
            List<Intent> pi = data.createTypedArrayList(Intent.CREATOR);
            boolean notResumed = data.readInt() != 0;
            boolean isForward = data.readInt() != 0;
            scheduleLaunchActivity(intent, b, ident, info, state, ri, pi,
                    notResumed, isForward);
            return true;
        }
    }
}

,调用scheduleLaunchActivity方法:

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
        ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
        List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
    ActivityClientRecord r = new ActivityClientRecord();
    r.token = token;
    r.ident = ident;
    r.intent = intent;
    r.activityInfo = info;
    r.state = state;
    r.pendingResults = pendingResults;
    r.pendingIntents = pendingNewIntents;
    r.startsNotResumed = notResumed;
    r.isForward = isForward;
    queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}

,创建一个ActivityClientRecord,并调用queueOrSendMessage方法,向Handler发送LAUNCH_ACTIVITY信息

step 36 执行queueOrSendMessage方法,向ActivityThread发送LAUNCH_ACTIVITY类型的信息

step 37 执行queueOrSendMessage方法,向mH发送LAUNCH_ACTIVITY类型的信息

step 38 mH接受到消息后,通过handleMessage执行代码:

public void handleMessage(Message msg) {
    if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
    switch (msg.what) {
        case LAUNCH_ACTIVITY: {
            ActivityClientRecord r = (ActivityClientRecord)msg.obj;
            r.packageInfo = getPackageInfoNoCheck(
                    r.activityInfo.applicationInfo);
            handleLaunchActivity(r, null);
        } break;
    }
}

,调用ActivityThread.handleLaunchActivity方法:

private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        ...
        handleResumeActivity(r.token, false, r.isForward);
        ...
    } else {
        ...
    }
}

,方法首先调用了performLaunchActivity方法

step 39 执行performLaunchActivity方法:

private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        r.intent.setExtrasClassLoader(cl);
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        ...
    }
    try {
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        ...
        if (activity != null) {
            ...
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstance,
                    r.lastNonConfigurationChildInstances, config);
            ...
            mInstrumentation.callActivityOnCreate(activity, r.state);
            ...
            r.activity = activity;
            r.stopped = true;
            if (!r.activity.mFinished) {
                activity.performStart();
                r.stopped = false;
            }
            ...
        }
        r.paused = true;
        mActivities.put(r.token, r);
    } 
    ...
    return activity;
}

,首先,通过反射创建了一个Activity的实例,调用其attachapplication

step 40 执行attach方法:

final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
        Application application, Intent intent, ActivityInfo info, CharSequence title, 
        Activity parent, String id, Object lastNonConfigurationInstance,
        Configuration config) {
    attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
        lastNonConfigurationInstance, null, config);
}

final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        Object lastNonConfigurationInstance,
        HashMap<String,Object> lastNonConfigurationChildInstances,
        Configuration config) {
    attachBaseContext(context);
    //activity信息设置
    ...
}

step 41 完成attach后,通过调用Instrumentation.callActivityOnCreate方法:

public void callActivityOnCreate(Activity activity, Bundle icicle) {
    ...
    activity.onCreate(icicle);
    ...
}

,调用了ActivityonCreate方法,至此,完成了Activity的启动

step 42step 29中,执行了main方法中的attach方法,在attach执行完后,执行 Looper.loop()

从Activity中启动同一进程中的另一Activity

基本与从Laucher中启动Activity的流程相同, 不同的是:

  1. step 9 中,由于Activity指定的进程为存在,于是 newTask == false并设置r.task = sourceRecord.task
  2. step 10 中,在Activity Stack中从上至下搜索一个与当前Activity同进程的Activity的位置i,并设置插入位置addPos=i+1
  3. step 26 中,由于Activity所在的进程已经启动,于是app != null && app.thread != null的结果为true,于是执行该选择语句下的realStartActivityLocked

从Activity中启动另一进程中的另一Activity

与从Laucher中启动Activity的过程一致

Activity热启动

s