【Android】Activity的启动流程

activity启动流程.jpg

1. startActivityForResult

Activity中的startActivity()方法有多种重载方法,但是无论以任何方式启动,最终都会调用startActivityForResult()方法

startActivityForResult()方法中会调用Instrumentation中的execStartActivity()方法

 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,         //getApplicationThread()
                    intent, requestCode, options);
        } 
        ...
    }

另外在startActivityForResult()方法中会传入ApplicationThread参数,在后续的方法中会用到

2. execStartActivity

execStartActivity中会调用ActivityManagerNative类的getDefault()方法

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        ...
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess();
            int result = ActivityManagerNative.getDefault()        //获取AMS
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
        }
        return null;
    }

这里可以看做是一个AIDL结构
ActivityManagerNative是一个继承自Binder并实现了IActivityManager接口的抽象类,实际上其为IActivityManager的Stub类(Stub类详见AIDL结构)

3. getDefault

getDefault()中会获取静态变量gDefault,gDefault的具体初始化如下:

    private static final Singleton gDefault = new Singleton() {
        protected IActivityManager create() {
            IBinder b = ServiceManager.getService("activity");        //通过ServiceManager获取到AMS
            if (false) {
                Log.v("ActivityManager", "default service binder = " + b);
            }
            IActivityManager am = asInterface(b);                     //将AMS转化为IActivityManager
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
            return am;
        }
    };
}


static public IActivityManager asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IActivityManager in =
            (IActivityManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }

        return new ActivityManagerProxy(obj);           //将AMS作为参数传入,作为IBinder对象被ActivityManagerProxy持有
    }

首先通过ServiceManager获取到ActivityManagerService(简称AMS), 再调用asInterface(b)以AMS为参数构建ActivityManagerProxy对象

在ActivityManagerProxy请求调用Service方法时,其中的transact()方法会让AMS执行相应方法(如startActivity()方法)

4. startActivity

AMS的startActivity()方法会转到ActivityStackSupervisor类中执行,再跳转到ActivityStack类中执行,然后又跳转回ActivityStackSupervisor,中间过程比较复杂

但最后会执行ActivityStackSupervisor中的realStartActivityLocked()方法

final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {
            ...
            ProfilerInfo profilerInfo = profileFile != null
                    ? new ProfilerInfo(profileFile, profileFd, mService.mSamplingInterval,
                    mService.mAutoStopProfiler) : null;
            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP);
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                    r.compat, r.launchedFromPackage, r.task.voiceInteractor, app.repProcState,
                    r.icicle, r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);
           ...
}

realStartActivityLocked()中会调用ApplicationThread中的scheduleLauchActivity()

5. scheduleLauchActivity

ApplicationThread对象继承于ApplicationThreadNative,ApplicationThreadNative继承自Binder并实现了IApplicationThread接口,同样可视为Service

scheduleLauchActivity()方法中将启动Activity的消息交由Handler H 进行处理

Handler H 中在处理启动Activity消息时,调用ActivityThread中的performLaunchActivity方法

6. performLaunchActivity

performLaunchActivity()中主要有以下步骤

从ActivityClientRecord中获取待启动Activity的组建信息

通过Instrumentation的newActivity方法使用反射的方式创建Activity对象

根据ActivityThread创建ContextImpl(appContext)

通过Instrumentation的newApplication方法使用反射的方式创建Application对象,若Application对象已经被创建,则不会重复创建

7. onCreate

通过Instrumentation调用Activity的各生命周期方法。

你可能感兴趣的:(【Android】Activity的启动流程)