关于Activity的onCreate方法是如何被执行的

本文详细解析了Android应用从启动到Activity显示的全过程,重点介绍了ActivityThread、ActivityManagerService等核心组件的工作机制。

首先要明确,一个应用真正的入口是ActivityThread的main方法,其中关键的代码如下

public static void main(String[] args) {
   //......省略部分无关代码......
   ActivityThread thread = new ActivityThread();
   thread.attach(false);
   //......省略部分无关代码......
 }

再看attach方法中的重要代码

final ApplicationThread mAppThread = new ApplicationThread();
private void attach(boolean system) {
     //......省略部分无关代码......
     final IActivityManager mgr = ActivityManagerNative.getDefault();
     try {
           mgr.attachApplication(mAppThread);
      } catch (RemoteException ex) {
            // Ignore
     }
     //......省略部分无关代码......       
}
这里需要注意的是,ActivityManagerNative.getDefault()返回的是一个ActivityManagerService对象(简称AMS)。

我们再来看AMS的attachApplication方法

@Override
public final void attachApplication(IApplicationThread thread) {
   synchronized (this) {
      int callingPid = Binder.getCallingPid();
      final long origId = Binder.clearCallingIdentity();
      attachApplicationLocked(thread, callingPid);
      Binder.restoreCallingIdentity(origId);
    }
}
其中调用了attachApplicationLocked方法,该方法逻辑比较长,但是比较重要的部分就是bindApplication和attachApplicationLocked这两个方法
private final boolean attachApplicationLocked(IApplicationThread thread,int pid) {
    thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
                    profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
                    app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
                    isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(mConfiguration), app.compat,
                    getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked());

    try {
         if (mStackSupervisor.attachApplicationLocked(app)) {
             didSomething = true;
         }
     } catch (Exception e) {
         Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
         badApp = true;
      }
       
}

bindApplication方法的参数很多,其主要作用就如方法的名字一样,绑定应用唯一的Application。查看ApplicationThread的bindApplication方法,关键代码如下

sendMessage(H.BIND_APPLICATION, data);

然后调用ActivityThread对象的handleBindApplication方法

private void handleBindApplication(AppBindData data) {
        try {
            Application app = data.info.makeApplication(data.restrictedBackupMode, null);
            try {
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
               
            }
        } finally {
            
        }
 }

data.info为LoadedApk的对象,如下是LoadedApk的makeApplication方法

public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        try {
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
        } catch (Exception e) {
           
        }
        return app;
}

然后调用Instrumentation的newApplication方法

static public Application newApplication(Class<?> clazz, Context context)
            throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        Application app = (Application)clazz.newInstance();
        app.attach(context);
        return app;
}

再调用Application的attach方法

final void attach(Context context) {
        attachBaseContext(context);
        mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}
最终调用了Application的attachBaseContext方法

下面我们再来看看mStackSupervisor.attachApplicationLocked方法,这个mStackSupervisor指向的是ActivityStackSupervisor类的对象,该方法中最重要的代码如下

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
   if (realStartActivityLocked(hr, app, true, true)) {
       didSomething = true;
   }
}
从realStartActivityLocked方法名可以看出,在其内部处理了“真正”启动Activity的逻辑

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(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
                    task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                    newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);

}
realStartActivityLocked方法中首先会准备启动Activity的参数信息,准备完毕后调用ApplicationThread的scheduleLaunchActivity方法

@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.token = token;
     r.ident = ident;
     r.intent = intent;
     r.referrer = referrer;
     r.voiceInteractor = voiceInteractor;
     r.activityInfo = info;
     r.compatInfo = compatInfo;
     r.state = state;
     r.persistentState = persistentState;

     r.pendingResults = pendingResults;
     r.pendingIntents = pendingNewIntents;

     r.startsNotResumed = notResumed;
     r.isForward = isForward;

     r.profilerInfo = profilerInfo;

     r.overrideConfig = overrideConfig;
     updatePendingConfiguration(curConfig);

     sendMessage(H.LAUNCH_ACTIVITY, r);
}
scheduleLaunchActivity方法逻辑很简单,对启动的信息进行准备,然后通过sendMessage方法发送一个消息,ActivityThread的内部类H进行接收并处理

private class H extends Handler {
   public static final int LAUNCH_ACTIVITY = 100;
        
   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);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
                
     }

}

然后调用handleLaunchActivity方法

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
     //省略无关代码   
    Activity a = performLaunchActivity(r, customIntent);
    //省略无关代码 
 }
performLaunchActivity才是我们分析的重点,其内部真正处理Activity的具体启动逻辑

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                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);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

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

        return activity;
    }
其中mInstrumentation.callActivityOncreate方法的调用就会执行对Activity的onCreate调用


总结一下流程,如下图









评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值