源码分析:Activity的启动过程(2)

2019-04-26  本文已影响0人  MrFengZH

ActivityStackSupervisor#realStartActivityLocked(以下源码都是基于API25)

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, new Configuration(mService.mConfiguration),
                new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
                task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
        
        //...                
    }
public final class ActivityThread {
    private class ApplicationThread extends ApplicationThreadNative {...}
}
    
public abstract class ApplicationThreadNative extends Binder
        implements IApplicationThread  {...}

ActivityThread.ApplicationThread#scheduleLaunchActivity

    // we use token to identify this activity without having to send the
    // activity itself back to the activity manager. (matters more with ipc)
    @Override
    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) {

        updateProcessState(procState, false);

        ActivityClientRecord r = new ActivityClientRecord();

        //一些r的配置
        
        updatePendingConfiguration(curConfig);

        sendMessage(H.LAUNCH_ACTIVITY, r);  //H是ActivityThread的一个内部类,其继承自Handler
    }

该方法的实现很简单,就是发送一个启动activity的消息交给H处理。

ActivityThread.H#handleMessage

    private class H extends Handler {
        //...
        
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");   //继续调用
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
                
                //...
            }
    }

H对这条消息的处理是:调用ActivityThread的handleLaunchActivity方法启动activity

ActivityThread#handleLaunchActivity

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        //...

        Activity a = performLaunchActivity(r, customIntent);    

        if (a != null) {
            //...
            
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

        } else {
            //...
        }
    }

其中,performLaunchActivity方法最终完成了activity对象的创建和启动,并且通过handleResumeActivity方法来调用该activity对象的onResume这一生命周期方法。

ActivityThread#performLaunchActivity

该方法主要完成了这几件事:

1. 从ActivityClientRecord中获取待启动的activity的组件信息

2. 通过Instrumentation的newActivity方法使用类加载器创建Activity对象

    Activity activity = null;
    try {
        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);    //创建Activity对象并最终返回该对象
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        //...
    }

3. 通过LoadedApk的makeApplication方法来尝试创建Application对象

    Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    //r是一个ActivityClientRecord(ActivityThread的静态内部类)对象
    //r.packageInfo是一个LoadedApk对象

LoadedApk#makeApplication

    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {     //如果已经创建过Application,就直接返回该Application
            return mApplication;
        }

        Application app = null;

        try {
            //...
            
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);  
            //与创建Activity对象类似,创建Application对象也是通过Instrumentation并使用类加载器完成的
                    
        } catch (Exception e) {
            //...
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

        if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);   //调用Application的onCreate方法
            } catch (Exception e) {
                //...
            }
        }

        return app;
    }

可以看出,如果之前已经创建过Application对象,就直接返回该对象,这保证了一个应用只有一个Application对象。Application对象创建完毕后,会通过Instrumentation的callApplicationOnCreate方法来调用Application的onCreate方法

4. 创建ContextImpl对象并通过Activity的attach方法来完成一项重要数据的初始化

    Context appContext = createBaseContextForActivity(r, activity);     //最终返回的是ContextImpl对象
    
    //...
    
    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);

5. 调用Activity的onCreate方法

    if (r.isPersistable()) {
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }

Activity的onCreate方法的调用,也意味着Activity已经完成了整个启动过程。

参考

上一篇下一篇

猜你喜欢

热点阅读