Android进阶解密①——activity的启动过程

Activity的启动分为根activity启动和普通activity启动,根activity的启动过程包括了普通activity的启动过程,本文只介绍根activity的启动;

根Activity启动的整理流程:

  1. Launcher进程请求SystemServer进程的AMS
  2. AMS请求用户进程的ApplicationThread
  3. ApplicationThread请求ActivityThread,ActivityThread启动Activity

步骤1,Launcher请求AMS

Launcher进程 ~> AMS
在Launcher桌面点击应用图标会调用Launcher的startActivitySafely()
    boolean startActivitySafely(View v, Intent intent, Object tag) {
        boolean success = false;
        try {
            success = startActivity(v, intent, tag);
        }
        return success;
    }

  boolean startActivity(View v, Intent intent, Object tag) {
        //  分析1
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        // 分析2
        startActivity(intent, opts.toBundle());
    }
  • 通过intent设置New Task的Flag,开启一个新的活动栈
  • 调用startActivity(),这个方法在Activity类中实现;

Activity:

startActivity()会调用startActivityForResult()

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

在Activity类中,将启动Activity的请求交给了Instrumentation类

Instrumentation:

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {

           int result = ActivityManager.getService()
                .startActivityAsUser(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, resultWho,
                        requestCode, 0, null, options, user.getIdentifier());

    }

通过 ActivityManager.getService()拿到iActivityManager对象,iActivityManager是AMS在用户进程的代理,所以真实调用的其实是AMS的startActivityAsUser();
至此Launcher到AMS的流程分析完毕

步骤2,AMS到ApplicationThread

AMS ~> 用户进程

AMS:

    @Override
    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) {
            //  分析1
            userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                userId, false, ALLOW_FULL_ONLY, "startActivity", null);

        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null);
    }
  • 首先AMS会通过userId字段检查调用者的权限
  • 在AMS中调用了mActivityStarter的startActivityMayWait()

ActivityStarter:

    final 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, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask, String reason) {
...
      //  分析1
       ProcessRecord callerApp = null;
       if (caller != null) { 
            callerApp = mService.getRecordForAppLocked(caller);
        }

           //  分析2
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, container, options, sourceRecord);

        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                options, inTask, outActivity);
    }

在Activity的第一个startActivity()中,主要做了两件事:

  • 通过AMS获取ProcessRecord对象,ProcessRecord用于记录调用者进程的信息;
  • 创建ActivityRecord对象,ActivityRecord用于记录启动Activity的信息,并传给下一个startActivity();
ActivityStarter的第二个startActivity()直接调用了startActivityUnchecked()

ActivityStarter.startActivityUnchecked():

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
...
        // 分析1
        // Should this be considered a new task?
        int result = START_SUCCESS;
        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            newTask = true;
            result = setTaskFromReuseOrCreateNewTask(
                    taskToAffiliate, preferredLaunchStackId, topStack);
        } 
                  //分析2
                    mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
}

startActivityUnchecked()主要处理与栈管理的相关逻辑:

  • 通过intent的flag判断是否需要开启新的活动栈,如果条件满足,就会在setTaskFromReuseOrCreateNewTask()内部创建一个TaskRecord用来描述新的Activity任务栈;

  • 调用StackSupervisor.resumeFocusedStackTopActivityLocked();

StackSupervisor.resumeFocusedStackTopActivityLocked():
    boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        //  分析1
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {
            //  分析2
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.state == RESUMED) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }
  • 获取要启动的Activity信息(ActivityRecord)
  • 调用ActivityStack.resumeTopActivityUncheckedLocked();
ActivityStack.resumeTopActivityUncheckedLocked():
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        boolean result = false;
        try {
            result = resumeTopActivityInnerLocked(prev, options);
        }
        return result;
    }


    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...        
        mStackSupervisor.startSpecificActivityLocked(next, true, false);
...
    }

StackSupervisor.startSpecificActivityLocked():

   void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        //  分析1
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);
                // 分析2
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
...
    }
  • 获取启动activity进程信息(ProcessRecord)
  • 调用realStartActivityLocked(), real start
StackSupervisor.realStartActivityLocked():
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
...
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
                    // TODO: Have this take the merged configuration instead of separate global and
                    // override configs.
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);
...
      }
  • 调用ProcessRecord的thread成员变量的scheduleLaunchActivity(),app.thread是用户进程的ApplicationThread在AMS进程的代理,实际调用的是用户进程的ApplicationThread.scheduleLaunchActivity()

步骤3,ApplicationThread通知ActivityThread启动Activity

ApplicationThread ~> ActivityThread

ApplicationThread

    private class ApplicationThread extends IApplicationThread.Stub {
...
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                int procState, Bundle state, PersistableBundle persistentState,
                List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
...
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }
...
  }
  • ApplicationThread是ActivityThread的一个内部类,这个类继承了aidl的Stub类,是一个Binder对象,用于和AMS进程的进程间通信,是AMS进程app.thread代理对象的真实对象;
  • ApplicationThread发送了一个主线程Handler消息,H

主线程的消息循环机制会处理到这个消息:

处理消息的地方是H的handleMessage里面,对应的处理逻辑:

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


    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        //  分析1
        Activity a = performLaunchActivity(r, customIntent);
            //  分析2
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        }
    }
  • 调用performLaunchActivity()创建activity对象,并做初始化操作:构建activity对象,构建Application对象,调用activity的onCreate,onStart()
  • 将activity的状态设置为resume;
performLaunchActivity():

这个方法超级重要,是启动Activity的核心实现方法,看代码:

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
            //  分析1
            Activity activity = null;
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);

          //  分析2
           Application app = r.packageInfo.makeApplication(false, mInstrumentation);

             //   分析3
             mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);

             //   分析4
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }

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