Activity启动流程(基于Android10附关键代码及流程图)

我们在平常开发的过程中,想启动一个Activity怎么办?startActivity(Intent intent)就可以了,这是一个简单得不能在简单的问题了。但如果问你启动一个Activity具体经过了哪些步骤,即时在同一App内调用startActivity是否用到了进程间通信呢?是不是有点蒙,我一个App内启动一个Activity还会用到进程间通信,要搞基(什么)?那么,我们就具体来看一看吧,也许这种知识在99%的开发中我们都不可能会用到,但多了解一些对我们也没什么坏处吧。
先上一张启动调用图吧,有点乱,将就看吧。谁让俺们对画这种图不专业呢。
Activity启动流程(基于Android10附关键代码及流程图)_第1张图片
毫无疑问,不管你是继承的什么Activity,启动都是从startActivity开始
Activity类

public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
//内部的重载方法
public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }
//调用到startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }
//又调用了重载的startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options){
            //关键代码
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            }

调用mInstrumentation.execStartActivity这时候进入到了Instrumentation类
Instrumentation类

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options){
            //关键代码
     int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
}

看下ActivityTaskManager类 调用getService的内容如下

public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };

注意看IActivityTaskManagerSingleton里面实例的时候得到的是IBinder,是否似曾相识?AIDL用过没?一模一样的用法。注意,这时候开始我们进入系统的进程,已经不在本进程了哈。正式登陆火星。

public class ActivityTaskManagerService extends IActivityTaskManager.Stub

这里贴出这个类的关系主要是表明ActivityTaskManagerService就是IActivityTaskManager.Stub
这时候我们有得进到ActivityTaskManagerService这个类了,找startActivity这个方法

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());
    }
//调用startActivityAsUser
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }
 //调用重载方法startActivityAsUser
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){
            //关键代码
     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();
 }

obtainStarter返回一个ActivityStarter类实例,注意下setMayWait这个,对我们后续流程分支有影响。
ActivityStarter类

//setMayWait将mayWait设置为了true
ActivityStarter setMayWait(int userId) {
        mRequest.mayWait = true;
        mRequest.userId = userId;

        return this;
    }
int execute() {
        try {
			//setMayWait决定了我们将走if分支  参数多得一匹
            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 {
                //
        } finally {
            onExecutionComplete();
        }
    }
private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
            Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
            IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
            int userId, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart){
            //关键代码
     int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                    allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                    allowBackgroundActivityStart);
 }
 //进入到这个方法
 private int 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){
      //关键代码
      mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                allowBackgroundActivityStart);
 }
 //进入这个重载方法
 private int 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, boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart){
      //关键代码
      final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
 }
 //又进入了这个重载,好吧,我承认我有点晕车
 private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity){
     //关键代码
     result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
}
//调用startActivityUnchecked
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity){
       //关键代码
       if (dontStart) {
         	//非常关键  前面我们都会找到startActivity系列,但这里需要从这里走,不然会迷路的
            if (mDoResume) {
                mRootActivityContainer.resumeFocusedStacksTopActivities();
            }
      }
 }

进入RootActivityContainer类

boolean resumeFocusedStacksTopActivities() {
        return resumeFocusedStacksTopActivities(null, null, null);
    }
//调用重载方法
boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions){
     //关键代码
     if (targetStack != null && (targetStack.isTopStackOnDisplay()
                || getTopDisplayFocusedStack() == targetStack)) {
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
}

targetStack是ActivityStack类的实例,所以进入ActivityStack类了

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options){
	//关键代码
	try {
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
            mInResumeTopActivity = false;
        }
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options){
	//关键代码
	mStackSupervisor.startSpecificActivityLocked(next, true, true);
}

进入ActivityStackSupervisor类

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig){
	//关键代码
	try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }
}
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException{
      //关键代码
      // Schedule transaction.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
 }

mService是ActivityTaskManagerService的实例 getLifecycleManager

ClientLifecycleManager getLifecycleManager() {
        return mLifecycleManager;
    }

返回的是ClientLifecycleManager
进入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();
        }
    }

transation是ClientTransation的实例,进入到了ClientTransaction类

public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

看下mClient的定义

private IApplicationThread mClient;

是不是瞬间千万匹飘过,点不进去了啊。莫慌,他明显是一个接口类,而且前面我们不是看到了AIDL么,感觉是不是要让我们回地球的感觉了呢?
其实现类在ActivityThread类的一个内部类ApplicationThread,看下这个类吧

private class ApplicationThread extends IApplicationThread.Stub 

嗯嗯,又给续上了。而且成功让我们从火星回到了地球(我们的APP进程)

public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }

嗯,这里面就一句代码,调用了 ActivityThread.this.scheduleTransaction(transaction);
其调用了父类ClientTransactionHandler的

void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

发送了消息而且也明确给我们了在ActivityThread.H类里面
在H类里面进行了处理

case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    //关键代码
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        transaction.recycle();
                    }
                    break;

mTransactionExecutor是什么呢?

private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);

这是定义在ActivityThread类里的,并传入this进行的实例。这点非常关键
进入到TransactionExecutor类

public void execute(ClientTransaction transaction){
	//关键代码
	executeCallbacks(transaction);
}
public void executeCallbacks(ClientTransaction transaction){
	//关键代码
	final ClientTransactionItem item = callbacks.get(i);
	item.execute(mTransactionHandler, token, mPendingActions);
}

item是ClientTransactionItem的实例

public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {
    /** Get the state that must follow this callback. */
    @LifecycleState
    public int getPostExecutionState() {
        return UNDEFINED;
    }
    @Override
    public int describeContents() {
        return 0;
    }
}

但是ClientTransactionItem这个也太抽象了吧,没有任何我们需要的信息啊
那么只能从callbacks那入手了,嗯,这部份得追溯到前面很远的代码,直接上结果吧

public class LaunchActivityItem extends ClientTransactionItem

这里的item其实就是LaunchActivityItem这个类

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);
    }

client是ClientTransactionHandler 的实例,这里传过来的其实就是ActivityThread这个类对象实例

public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent){
     //关键代码
     final Activity a = performLaunchActivity(r, customIntent);
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent){
	//关键代码
	//创建Activity实例
	activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
    //OnCreate
    if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
}

嗯,又调到了Instrumentation这个类了

public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        //这句是关键
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

成功拉回了我们最熟悉的Activity类

final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
//调用重载类
final void performCreate(Bundle icicle, PersistableBundle persistentState){
	//关键代码
	if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
}
//在调用我们最最熟悉的onCreate
protected void onCreate(@Nullable Bundle savedInstanceState){
}

哈哈,虽然很懵,但还算是将整个流程走完了。整个流程只看了我们所希望的关键代码,也没有去理解其中代码的含义(确实太火星了,理解不了啊),但也对我们了解Activity的整个启动流程以及启动过程中所调用的关键类还是有所了解的。而且看完之后我们也知道了哪怕是在APP内启动Activity其实也是通过AIDL通过系统级来完成的。
其实平时我们所调用的一个看似简单的API,其内部流程还是那么的复杂,只叹自己太LOW吧!

你可能感兴趣的:(学习笔记)