Activity启动基本流程分析

1.概述

基于Android9.0(SDK 28)源码。
关键类:

ActivityThred
ApplicationThread
ActivityManagerService
ProcessRecord 进程信息
ActivityRecord Activity信息
ActivityStack
ActivityStackSupervisor
LoadApk

2.Activity类中流程分析

2.1 Activity->startActivity()

 @Override
 public void startActivity(Intent intent, @Nullable Bundle options) {
     if (options != null) {
      startActivityForResult(intent, -1, options);
    } else {
       //startActivity(Intent):requestCode是-1了
       startActivityForResult(intent, -1); //2.2 Activity->startActivityForResult()
     }
}

2.2 Activity->startActivityForResult()

//requestCode=-1
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, Bundle options) {
       ...
       //转调到Instrumentation的execStartActivity()
       Instrumentation.ActivityResult ar =
              mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, 
              this, intent, requestCode, options);
       ...
}
  • mMainThread.getApplicationThread():
    mMainThread是ActivityThread类型的实例,getApplicationThread获取的是ActivityThread的内部类ApplicationThread类型的实例,ApplicationThread实际上也是IPC调用,对应的AIDL文件是IApplicationThread.aidl。

3 Instrumentation类中流程

Activity->startActivityForResult()方法中转调到了Instrumentation->execStartActivity():

public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) { 
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    ...
    //result是执行启动后的结果,类似于错误码,标记不同的错误类型
    //从这里调用了ActivityManagerService的startActivity(),是ipc调用,ActivityManager.getService()是通过单例模式实现的
    int result = ActivityManager.getService().startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
    //根据AMS启动Activity的result值,进行错误的处理,如果启动失败会抛出各种类型的异常,成功则直接return
    checkStartActivityResult(result, intent);
}

public class ActivityManagerService extends IActivityManager.Stub implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        ...
}
  • ActivityManager.getService().startActivity()这个调用,是将whoThread(ActivityThread.ApplicationThread)接口引用传到了AMS中。
  • ActivityManager.getService()实际上获取的是AMS的实例。

4 转到SystemServer进程中:ActivityManagerService->startActivity()

AMS中startActivity()最后会转调到startActivityAsUser():

 public final 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) {
        ...
        //这里先转调ActivityStartController进行userId检查
        userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,  Binder.getCallingPid(), 
        Binder.getCallingUid(), "startActivityAsUser");
        //又转调到ActivityStarter的execute()方法
        return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId) //mRequest.mayWait = true;会直接将mayWait标记为true
                .execute();
    }

2.5 ActivityStarter->execute(),会继续调用到ActivityStarter->startActivityMayWait()方法

  • 2.5.1 ActivityStarter->startActivityMayWait()
private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, 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) {
            ...
            //转调startActivity()
            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);
            ...
            } 
  • 2.5.2 ActivityStarter->startActivity()
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) {
        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);
        return getExternalResult(mLastStartActivityResult);
    }
  • 2.5.3 ActivityStarter->startActivity()
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,...) {
    //这里startActivity()传入的Bundle类型的option参数由ActivityOptions进行管理了
    final Bundle verificationBundle = options != null ? options.popAppVerificationBundle() : null;
    ProcessRecord callerApp = null;
     return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity);
  • 2.5.4 ActivityStarter->startActivity()
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
        int result = START_CANCELED;
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, outActivity);
        return result;
    }
  • 2.5.5 ActivityStarter-> startActivityUnchecked():
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
       if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            newTask = true;
            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
        } else if (mSourceRecord != null) {
            result = setTaskFromSourceRecord();
        } else if (mInTask != null) {
            result = setTaskFromInTask();
        } else {
            setTaskToCurrentTopOrCreateNewTask();
        }
        if (mDoResume) {
            final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
                mService.mWindowManager.executeAppTransition();
            } else {    
                //流程转调到ActivityStackSupervisor类的resumeFocusedStackTopActivity()方法
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
            }
        }
                    
}
  • mSupervisor:ActivityStackSupervisor,Activity栈的管理者。

3.ActivityStackSupervisor中的流程

  • 3.1 ActivityStackSupervisor::resumeFocusedStackTopActivityLocked():
boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        //获取要启动Activity所在栈的栈顶的不是处于停止状态的Activiy的ActivityRecord
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || !r.isState(RESUMED)) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.isState(RESUMED)) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }

4.ActivityStack中的流程

4.1ActivityStack->resumeTopActivityUncheckedLocked()

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        ...
        boolean result = false;
        result = resumeTopActivityInnerLocked(prev, options);
        return result;
    }

4.2ActivityStack->resumeTopActivityInnerLocked()

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next.app != null && next.app.thread != null) {
                mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
}

4.3 ActivityStackSupervisor->startSpecificActivityLocked()

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    //用进程名拿到ProcessRecord实例
     ProcessRecord app = mService.getProcessRecordLocked(r.processName,  r.info.applicationInfo.uid, true);
     if (app != null && app.thread != null) {
         realStartActivityLocked(r, app, andResume, checkConfig);
     }           
}

4.4 ActivityStackSupervisor->realStartActivityLocked()

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, 
boolean checkConfig) throws RemoteException {
     final TaskRecord task = r.getTask();
     final ActivityStack stack = task.getStack();       
     // 创建一个启动Activity的事务,并且将applicationThread传给ClienTransaction类中
     final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken);
     clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
     System.identityHashCode(r), r.info,
     mergedConfiguration.getGlobalConfiguration(),
     mergedConfiguration.getOverrideConfiguration(), r.compat,
     r.launchedFromPackage, task.voiceInteractor, app.repProcState,
     r.icicle, r.persistentState, results, newIntents, 
     mService.isNextTransitionForward(), profilerInfo));
    
    final ActivityLifecycleItem lifecycleItem;
    if (andResume) {
         lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
     } else {
         lifecycleItem = PauseActivityItem.obtain();
     }
    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    //1.以事务的形式转发
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
  • 1.这里的mService就是AMS实例,mService.getLifecycleManager()获取的mLifecycleManager是在ActivityManagerService的构造函数中new出来的

4.5 ClientLifecycleManager->scheduleTransaction()

//ClientLifecycleManager::scheduleTransaction(),ClientTransaction实现了Parcelable接口,所以支持跨进程传输
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        //ClinetTransaction会直接调用IApplicationThread的scheduleTransaction(ClinetTrasaction),
       //IApplicationThread的实现类是ActivityThread的内部类ApplicationThread
        transaction.schedule(); 
        if (!(client instanceof Binder)) {
            transaction.recycle();
        }
  }
  • ClientTransaction
//ActivityStackSupervisor->realStartActivityLocked()中: ClientTransaction.obtain(app.thread, r.appToken)的app.thread对象
private IApplicationThread mClient;
public IApplicationThread getClient() {
    return mClient;
}
public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

ApplicationThread->scheduleTransaction()

@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //ActivityThread中并没有scheduleTransaction()方法实现代码,
    //其实是调用了父类ClientTransactionHandler::scheduleTransaction()方法
     ActivityThread.this.scheduleTransaction(transaction);
}

ClientTransactionHandler::scheduleTransaction()方法

//ActivityThread是继承自ClientTransactionHandler
class ActivityThread extends ClientTransactionHandler {}
void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        //将事务发到H(Handler)了
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

//H::handleMessgae()
case EXECUTE_TRANSACTION:
      final ClientTransaction transaction = (ClientTransaction) msg.obj;
      //执行了TransactionExecutor的execute方法,会执行一个executeCallbacks(),
      //然后调用cycleToPath(),最终会调用到performLifecycleSequence()
      mTransactionExecutor.execute(transaction);
      if (isSystem()) {
            transaction.recycle();
      }
      break;
    }

TransactionExecutor::execute()->executeLifecycleState()->cycleToPath()->performLifecycleSequence()

//performLifecycleSequence(),通过TransactionHandler就可以回调到ActivityThread的各种生命周期方法了
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            log("Transitioning to state: " + state);
            switch (state) {
                case ON_CREATE:
                   //调用ActivityThread的handleLaunchActivity,会进一步调用创建Activity实例,回调Activity的onCreate方法等
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,null);
                    break;
                case ON_START:
                   //onStart()
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                case ON_RESUME:
                    //onResume()
                    mTransactionHandler.handleResumeActivity(r.token, false ,r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                   //onPause()
                    mTransactionHandler.handlePauseActivity(r.token, false , false , 0 , 
                    mPendingActions,  "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    //onStop()
                    mTransactionHandler.handleStopActivity(r.token, false,
                          0, mPendingActions, false ,"LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    //onDestroy()
                    mTransactionHandler.handleDestroyActivity(r.token, false ,
                            0, false ,"performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    //onRestart()
                    mTransactionHandler.performRestartActivity(r.token, false );
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }

从上述代码可以看出,ClientTrasactionHandler最后通过TransactionExecutor真正发起Activity的各种生命周期方法的调用,如果在创建Activity实例时,Application实例未被创建,就会先创建Application实例,二者都是通过类全限定名和ClassLoader完成实例的创建。

ActivityThread中的启动流程

  • Activity启动的核心方法: ActivityThread::performLaunchActivity()
//android.app.ActivityThread#performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
       //这个Context是Activity级别的
       ContextImpl appContext = createBaseContextForActivity(r);
        //1.使用Instrumentation和ClassLoader采用反射方式创建Activity实例
        Activity activity = null;
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
        //2.获取Application实例,如果为null同样会同样使用反射和classsLoader创建实例,是使用Instrumentation创建的,具体实现代码在:android.app.LoadedApk#makeApplication()
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
         ...
         //3.初始化Activity的关键参数
        activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
        //4.Activity,Application都创建完成了,转调Activity的onCreate()方法
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
         } else {
           mInstrumentation.callActivityOnCreate(activity, r.state);
        }
}

ContextImpl的创建时机,是怎么和Activity关联起来的?Activity重写的getSystemService()方法最终中间是由ContextImpl转调的,但是没有看大ContextImpl是怎么传到Activity内的。

//android.app.ActivityThread#performLaunchActivity()中有一段代码是这样:
 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ContextImpl appContext = createBaseContextForActivity(r);
    ...
    //这里将创建的ContextImpl实例传给了Activity
     activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
 }

Activity对象的创建过程

在ActivityThread::performLaunchActivity()中,调用了Instrumentation#newActivity()方法,这个就是开始创建Activity实例的开始。

//android.app.Instrumentation#newActivity(java.lang.ClassLoader, java.lang.String, android.content.Intent)
public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        String pkg = intent != null && intent.getComponent() != null
                ? intent.getComponent().getPackageName() : null;
        return getFactory(pkg).instantiateActivity(cl, className, intent);
}

AppComponentFactory->instantiateActivity:直接通过反射创建Activity对象

public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
            @Nullable Intent intent)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (Activity) cl.loadClass(className).newInstance();
}

Application对象的创建过程:LoadApk->makeApplication()

public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }
         Application app = null;
        String appClass = mApplicationInfo.className;
        //如果className为null就默认为android.app.Application
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }
        java.lang.ClassLoader cl = getClassLoader();
            if (!mPackageName.equals("android")) {
                initializeJavaContextClassLoader();  //检查创建PathClassLoader对象
       }
      ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
      app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
      appContext.setOuterContext(app);
}

参考文献
[1]http://gityuan.com/2016/03/12/start-activity/
[2]Android开发艺术探索,任玉刚
[3]Android进阶解密,刘望舒

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

推荐阅读更多精彩内容