Android-Activity 启动流程分析一

本文基于 api 28 分析
提问:从桌面点击图标开始 app 干了什么?

分析前先了解以下类:

Instrumentation: 在应用代码之前实例化,每个进程都有一个Instrumentation。监控应用与所有系统的交互,每个 Activity 持有它的引用,ActivityThread 要创建或暂停 Activity 时,都是通过 Instrumentation 进行操作。

ApplicationThread: 继承 IApplicationThread.Stub,ActivityThread 的内部类,是 ActivityManagerService 向 ActivityThread 通信的桥梁。

ActivityThread:继承 ClientTransactionHandler ,APP的主线程,main 函数。

ActivityRecord:每个 ActivityRecord 在 AMS 中对应一个 Activity,记录 Acitivty 信息。(一个 Activity 对应多个 ActivityRecord,因为同一个 Activity 可以被启动多次?此条待确定)

ActivityStarter:收集 intent、task、flag 等信息,生成 ActivityRecord。

TaskRecord:任务栈,先进后出,存储 ActivityRecord。一个 TaskRecord 由一个或者多个 ActivityRecord 组成。

ActivityStack:管理 TaskRecord,包含了多个TaskRecord,由 ActivityStackSupervisor 创建。

ActivityStackSupervisor:AMS 通过 ActivityStackSupervisor 操作 ActivityStack。

ActivityManagerService:(:IActivityManager:SystemServer) 系统中启动的独立进程,负责管理四大组件,可以利用 Binder 跟它通信。

ClientLifecycleManager:调用 ClientTransaction,让 AMS 切换到 APP 进程执行生命周期。

Activity 启动流程涉及到进程、线程间通信:
1、startActivity 时所在进程。
2、AMS 进程,通过 ApplicationThread 实现 AMS 与 ActivityThread 的进程间通信。

在 ActivityManagerService 中生成 ApplicationThread 代理
ActivityThread.attach()方法:
            //实例化 ApplicationThread、ActivityManagerService 本地代理
            final IActivityManager mgr = ActivityManager.getService();
            //将 ApplicationThread 绑定在 ActivityManagerService(通过 ProcessRecord) 中
            mgr.attachApplication(mAppThread, startSeq);
            mgr.attachApplicationLocked(thread)
            new ProcessRecord().makeActive(thread) 将 applicationThread 绑定在 ProcessRecord 中
            activityManagerServiec attach applicationThread

3、目标 Activity 进程,ActivityThread 中 Handler 线程间通信。

startActivity.png

图片来源:基于Android-28 的源码 Activity 启动流程分析

第一阶段:startActivity

1.1 第一种启动方式,桌面图标启动 startActivity,实现类是 ContextImpl。

class ContextImpl extends Context {
    public void startActivity(Intent intent) {
        ...
        startActivity(intent, null);
    }

    @Override
    public void startActivity(Intent intent, Bundle options) {
        warnIfCallingFromSystemProcess();
        ...
        //mMainThread 是 ActivityThread。mMainThread.getApplicationThread() 是获取 ActivityThread 的内部类ApplicationThread,它是一个 IBinder,主要用于 ActivityThread 与 AMS 的通信。
        mMainThread.getInstrumentation().execStartActivity(
                getOuterContext(), mMainThread.getApplicationThread(), null,
                (Activity) null, intent, -1, options);
    }
}

1.2 第二种启动方式,应用内打开 activity,实现类 Activity.

public class Activity extends ContextThemeWrapper{
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
             ...
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
             ...
}

由此可见 ContextImpl 与 Activity 最终都是通过 Instrumentation 的 execStartActivity() 启动 Activity。

public class Instrumentation {
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        ...
            int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        ...
    }
}

public class ActivityManager {
    public static IActivityManager getService() {
        return IActivityManagerSingleton.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;
                }
            };
}

ActivityManager.getService() 获取得到的是 IActivityManager 的接口,是 ActivityManagerService(AMS) 远程代理类。AMS 运行在另外一个进程,继承了 IBinder,是 binder 通信的 Server 端。通过 IActivityManager 就可以跟 AMS 实现 Binder 通信。

第二阶段:AMS 进程
public class ActivityManagerService extends IActivityManager.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());
    }

    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) {
        //mActivityStartController.obtainStarter 获取到 ActivityStarter
        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)
                .execute();

    }
}

ActivityStarter 收集 intent、选择启动的 task、flag 等信息,复用Activity等逻辑,生成 ActivityRecord。

class ActivityStarter {
    int execute() {
        ...
        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);
            }
    }

    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) {
        ...
        //构造当前的 Actiivty 的 ActivityRecord
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, checkedOptions, sourceRecord);
        ...
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity);
    }

    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
            ...
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        ...
        return result;
    }

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
          ...
          //mSupervisor 是 ActivityStackSupervisor
          mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
            }
          ...
    }
}

ActivityStarter 构造了ActivityRecord,选择ActivityStack等等。
startActivityUnchecked 做了决定任务栈,根据启动模式,是否调用deliverNewIntent,复用Activity 等动作。

public class ActivityStackSupervisor extends ConfigurationContainer {
    boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
            ...
            //targetStack 是 ActivityStack
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            ...
    }
}
class ActivityStack<T extends StackWindowController> extends ConfigurationContainer {
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
            ...//1
            result = resumeTopActivityInnerLocked(prev, options);
            ...
    }

    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        ...//2
        if (mResumedActivity != null) {
            //构造 PauseActivityItem 执行 pause 方法,暂停当前的 Activity
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
        if (pausing && !resumeWhilePausing) {
            ...
            return true;
        }
        ...
        if (next.app != null && next.app.thread != null) {
                        ...
                        //如果 Activity 已存在,执行 resume
                        mStackSupervisor.scheduleResumeTopActivities();
        } else {
            ...//3
            //创建进程,冷启动并创建 Activity。或者已启动 App,重新启动 Activity
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
}

resumeTopActivityInnerLocked() 主要负责暂停当前 Activity 和启动新的 Activity。

先来看 startPausingLocked 暂停 Activity 方法,再看 startSpecificActivityLocked 启动 Activity 方法


    final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean pauseImmediately) {
                ...
                //mService.getLifecycleManager() 是获取到 ClientLifecycleManager, 这个类负责执行 ActivityLifecycleItem,就是生命周期的任务,如 PauseActivityItem 、ResumeActivtyItem
                mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                        PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));
        }
    }

public class ActivityStackSupervisor extends ConfigurationContainer  {
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
         ...
        //如果 app 进程存在
        if (app != null && app.thread != null) {
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            }
        //如果 app 进程不存在
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);                ...
    }

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
                ...
                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) {//andResume 为 true
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                //lifecycleItem 是 ResumeActivtyItem
                clientTransaction.setLifecycleStateRequest(lifecycleItem);
                //mService.getLifecycleManager() ClientLifecycleManager
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
                ...
    }

}

这里分两种情况,一是 app 进程存在执行 realeStartActivityLocked() ,另一个是 app 进程不存在,执行 AMS 的 startProcessLocked() ,Zygote 进程 fork 子进程,启动进程执行 ActivityThread 的 main 方法。

class ClientLifecycleManager {
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        //执行 ClientTransaction 的 schedule() 方法
        transaction.schedule();
        ...
    }
}
public class ClientTransaction {
    public void schedule() throws RemoteException {
        //mClient  为 IApplicationThread,实际是 ActivityThread 中的 ApplicationThread
        mClient.scheduleTransaction(this);
    }
}

ClientTransaction 中包装了 ActivityLifecycleItem,就是生命周期的任务,如 PauseActivityItem 、ResumeActivtyItem。

IApplicationThread 是 ActivityThread 内部类 ApplicationThread,是 Binder 对象,IApplicationThread 是它远程接口。
当执行 ApplicationThread. scheduleTransaction() 会从 AMS 进程回到目标 Activity 进程。

接下来看 ApplicationThread

目标 Activity 进程,ActivityThread 中 Handler 线程间通信。
public final class ActivityThread extends ClientTransactionHandler {
    private class ApplicationThread extends IApplicationThread.Stub {
        //ApplicationThread 是 Binder 对象,IApplicationThread 是它远程接口。
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            //1
            ActivityThread.this.scheduleTransaction(transaction);
        }
    }

    //ActivityThread 继承自 ClientTransactionHandler,scheduleTransaction 是 ClientTransactionHandler 中方法
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        //2 发送消息 EXECUTE_TRANSACTION 
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        ...
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        //3,mH 是 Handler,将异步 msg 发送给 Handler 同步处理
        mH.sendMessage(msg);
    }

    class H extends Handler {
                ...
                //回到主线程,处理 EXECUTE_TRANSACTION 消息
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    //4、mTransactionExecutor 是 TransactionExecutor
                    mTransactionExecutor.execute(transaction);
                    break;
            }
        }
    }
}
public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
        ...
        //5、
        executeCallbacks(transaction);
        //6、
        executeLifecycleState(transaction);
    }

    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        ...
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            ...
            //5.1  
            if (closestPreExecutionState != UNDEFINED) {
                //预初始化状态 ON_CREATE/ON_START 等 
                cycleToPath(r, closestPreExecutionState);
            }
            //5.2 item 为 PauseActivityItem/ResumeActivityItem 等 ClientTransactionItem 类
            item.execute(mTransactionHandler, token, mPendingActions);
            //5.3
            item.postExecute(mTransactionHandler, token, mPendingActions);
        }
    }

    private void cycleToPath(ActivityClientRecord r, int finish,
            boolean excludeLastState) {
        ...
        performLifecycleSequence(r, path);
    }

    /** mTransactionHandler 是 ActivityThread,最终调用 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:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, false /* show */,
                            0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

}

至此,这一段讲了 ActivityLifecycleItem 通过 ClientLifecycleManager 走到 ActivityThread,并切换到主线程执行 execute()

参考:
基于Android-28 的源码 Activity 启动流程分析
ActivityRecord、TaskRecord、ActivityStack以及Activity启动模式详解
Activity生命周期回调是如何被回调的?
ActivityRecord、TaskRecord、ActivityStack以及Activity启动模式详解

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

推荐阅读更多精彩内容