Android 8.0 Activity 启动流程

从Activity 的启动流程不仅可以更加的熟悉Activity 的相关知识点,还可以学习架构设计的思想,设计模式,大型项目代码结构。。,所以Activity 启动流程还是很值得看一看的。

在应用层调用startActivity 后,会经过一系列的调用,经过进程间通信(IPC),调用到ActivityManagerService (AMS)的startActivity 方法,这样程序走到了系统服务进程这边,在系统服务完成一系列的注册,合法性检验等,最终会通过IPC 通知应用程序进程,可以开始创建目标Activity 了,接着回到目标Activity 的onCreate 方法。

上面已经宏观上,粗略的描述了一下Activity 的启动,带着对宏观了认识,我们再来细看具体的方法调用。

从Activity 的startActivity 开始,该方法有好几种重载方式,但它们最终会调用startActivityForResult 方法;

@Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }

@Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            startActivityForResult(intent, -1);
        }
    }

 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
  }

可以发现startActivity 方法会调用到startActivityForResult 方法。

startActivityForResult()

来看三个参数的startActivityForResult方法,这里省略其它部分,只展示了本篇文章要分析的部分源码:

//Activity.java
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, 
@Nullable Bundle options) {
    	    //...
            //调用Instrumentation的execStartActivity方法
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            //...
    }

Instrumentation 描述,是什么回事;描述,是什么回事;描述,是什么回事;描述,是什么回事;描述,是什么回事;

execStartActivity()

//Instrumentation.java
public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    //...
    try {
        //...
        //这里调用了ActivityManagerService的startActivity方法
        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);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

ActivityManager.getService()返回的是ActivityManagerService(下面简称AMS)在应用进程的本地代理,

//ActivityManager.java
public static IActivityManager getService() {
    	//IActivityManagerSingleton是Singleton类型,Singleton是一个单例的封装类
    	//第一次调用它的get方法时它会通过create方法来初始化AMS这个Binder对象,在后续调用中返回之前创建的对象
        return IActivityManagerSingleton.get();
}

 
  private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    //ServiceManager是服务大管家,这里通过getService获取到了IBinder类型的AMS引用
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    //这通过asInterface方法把IBinder类型的AMS引用转换成AMS在应用进程的本地代理
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
  };

ActivityManager.getService()返回是一个IActivityManager 的类型的Binder 对象,它的具体实现是ActivityManagerService (AMS),所以ActivityManager.getService() 的startActivity 方法后经过进程间通信(IPC),会调用到AMS 的startActivity 方法,程序也就会走到AMS所在的系统进程SystemServer ,这里就由应用进程传递到了系统服务,在系统服务那边完成对Activity 否“合法”的一系列检验工作,之后也会IPC 回调给应用进程,没有问题,就会跳转界面啦。

整个过程的时序图如下:

AMS::startActivity()

由上面可知,实际调用到了AMS 的startActivity 方法;

@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());
    }

只是调用了startActivityAsUser 方法,

AMS::startActivityAsUser()

@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) {
        enforceNotIsolatedCaller("startActivity");
        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                userId, false, ALLOW_FULL_ONLY, "startActivity", null);
        // TODO: Switch to user app stacks here.
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null,
                "startActivityAsUser");
    }

调用了 mActivityStarter.startActivityMayWait方法,mActivityStarter是ActivityStarter类型,它是AMS中加载Activity的控制类,会收集所有的逻辑来决定如何将Intent和Flags转换为Activity,并将Activity和Task以及Stack相关联。

ActivityStarter::startActivityMayWait()

//ActivityStarter.java
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) {
    //...
    // 保存一个副本,以防临时需要它
    final Intent ephemeralIntent = new Intent(intent);
    // 不要修改客户端的对象!
    intent = new Intent(intent);
    //...
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);
    if(rInfo == null){
        //...
    }
    //解析这个intent,收集intent指向的Activity信息
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    //...
    final ActivityRecord[] outRecord = new ActivityRecord[1];
    //调用了本身的startActivityLocked方法
    int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                    inTask, reason);
    //...
    return res;
}

ActivityInfo里面收集了要启动的Activity信息,

这里又调用了ActivityStarter 的startActivityLocked方法。

ActivityStarter::startActivityLocked()

//ActivityStarter.java
int startActivityLocked(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,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask, String reason) {
         //这里对上面传进来值为"startActivityAsUser"理由参数判空
         if (TextUtils.isEmpty(reason)) {
            throw new IllegalArgumentException("Need to specify a reason.");
        }
       mLastStartReason = reason;
       mLastStartActivityTimeMs = System.currentTimeMillis();
       mLastStartActivityRecord[0] = null;
      //调用了本身的startActivity方法
       mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                container, inTask);
      if (outActivity != null) {
            outActivity[0] = mLastStartActivityRecord[0];
        }
      return mLastStartActivityResult;
  }

ActivityStarter::startActivity()

 //ActivityStarter.java
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,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask) {
     int err = ActivityManager.START_SUCCESS;
     //...
     //获取调用者所在进程记录的对象
     ProcessRecord callerApp = null;
     if (caller != null) {
         //这里调用AMS的getRecordForAppLocked方法获得代表调用者进程的callerApp
         callerApp = mService.getRecordForAppLocked(caller);
         if (callerApp != null) {
             //获取调用者进程的pid与uid并赋值
             callingPid = callerApp.pid;
             callingUid = callerApp.info.uid;
         } else {
             err = ActivityManager.START_PERMISSION_DENIED;
         }
     }
     //下面startActivity方法的参数之一,代表调用者Activity的信息
     ActivityRecord sourceRecord = null;
     if (resultTo != null) {
            sourceRecord = mSupervisor.isInAnyStackLocked(resultTo);
         	//...
     }
     //...
     if (err == ActivityManager.START_SUCCESS && aInfo == null) {
            // We couldn't find the specific class specified in the Intent.
            // Also the end of the line.
            err = ActivityManager.START_CLASS_NOT_FOUND;
        }
     //...
     //创建即将要启动的Activity的信息描述类ActivityRecord
      ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, container, options, sourceRecord);
     if (outActivity != null) {
         outActivity[0] = r;
     }
     //...
     //调用了本身的另一个startActivity方法
	return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                options, inTask, outActivity);
 }

该 startActivity代码非常长,省略了很多,这个调用者进程,在这里就是应用程序进程,

ProcessRecord是用来描述一个应用进程的信息,

ActivityRecord是用来保存一个Activity的所有信息的类;

可以看到该方法调用了另一个ActivityStarter 的startActivity 方法,而且参数明显明显减少了,大多数有关要启动的Activity的信息都被封装进了ActivityRecord ,作为参数r传了进去。

 另一个ActivityStarter 的 startActivity 方法

 //ActivityStarter.java
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
     int result = START_CANCELED;
     try {
            mService.mWindowManager.deferSurfaceLayout();
         	//调用的startActivityUnchecked方法
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
          } finally {
           	//...
           mService.mWindowManager.continueSurfaceLayout();
     	}
     //...
	return result;
 }

ActivityStarter::startActivityUnchecked()

//ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
    //...
    //计算出启动Activity的模式,并赋值给mLaunchFlags
    computeLaunchingTaskFlags();
    //...
    //设置启动模式
     mIntent.setFlags(mLaunchFlags);
    //...
    boolean newTask = false;
    //1、下面会进行判断,到底需不需要创建一个新的Activity任务栈
    int result = START_SUCCESS;
    if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
        && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
        //1.1走这里就会在setTaskFromReuseOrCreateNewTask方法内部创建一个新的Activity任务栈
        newTask = true;
        result = setTaskFromReuseOrCreateNewTask(
            taskToAffiliate, preferredLaunchStackId, topStack);
    } else if (mSourceRecord != null) {
        //1.2走这里就会在setTaskFromSourceRecord方法内部获得调用者Activity的的任务栈赋值给mTargetStack
        result = setTaskFromSourceRecord();
    } else if (mInTask != null) {
        //1.3走这里就会在setTaskFromInTask方法内部直接把mInTask赋值给mTargetStack,前面已经说过mInTask等于null
        result = setTaskFromInTask();
    } else {
        //1.4、就是前面的条件都不满足了,但是这种情况很少发生
        setTaskToCurrentTopOrCreateNewTask();
    }
    if (result != START_SUCCESS) {
        return result;
    }
    //...
    //mDoResume等于上面传进来的doResume,为true
     if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
              //...
            } else {
              //正常的话会走到这里
                if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                //2、调用mSupervisor的resumeFocusedStackTopActivityLocked方法
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
            }
        } else {
           //...
        }
     return START_SUCCESS;
}

startActivityUnchecked方法也是很长,这个方法主要处理Activity栈管理相关的逻辑,

resumeFocusedStackTopActivityLocked()

//ActivityStackSupervisor.java
boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
       	//...
    	//获取要启动的Activity所在栈的栈顶的ActivityRecord
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
    	//1、r是否null或是否为RESUMED状态
        if (r == null || r.state != RESUMED) {
            //2、关注这里,调用ActivityStack的resumeTopActivityUncheckedLocked方法
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.state == RESUMED) {
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }

首先这里会获取要启动的Activity所在栈的栈顶的ActivityRecord赋值给r,因为目标Activity的还没有启动,所以此时栈顶就是调用者Activity;ActivityA 跳转到ActivityB 的话,ActivityA 的状态会从RESUME状态转换到其他状态,如STPO,满足(r == null || r.state != RESUMED) 会调用ActivityStack 的resumeTopActivityUncheckedLocked 方法;

ActivityStack:: resumeTopActivityUncheckedLocked()

//ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
       //...
        boolean result = false;
        try {
            //1、调用了本身的resumeTopActivityInnerLocked方法
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
           //...
        }
        //...
        return result;
    }

ActivityStack:: resumeTopActivityInnerLocked()

//ActivityStack.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        //...
    	//获得将要启动的Activity的信息
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */)
        //...
        if (next.app != null && next.app.thread != null) {
            //...
        }else{
            //...
            // 因为此时要启动的Activity还不属于任何进程,故它的ProcessRecord为空成立,就会走到else分支
            //1、调用了ActivityStackSupervisor的startSpecificActivityLocked方法
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
    	if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return true;
}

该方法调用到了ActivityStackSupervisor的startSpecificActivityLocked方法,又回到了ActivityStackSupervisor ;

ActivityStackSupervisor::startSpecificActivityLocked()

//ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
        //获取要启动的Activity的所在应用程序进程
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);
        r.getStack().setLaunchTime(r);
        //要启动的Activity的所在应用程序进程存在
        if (app != null && app.thread != null) {
            try {
                //...
                //1、调用了本身的realStartActivityLocked方法
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                //...
            }
        }
    	//...
    }

ActivityStackSupervisor::realStartActivityLocked()

realStartActivityLocked() 这个方法很关键,从它的名字也可以看出来,好像在说,绕了一大圈子,这次是真的Start Activity 了;

// ActivityStackSupervisor 
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
     //...
     //1、把应用所在进程信息赋值给要启动的Activity的ActivityRecord
     r.app = app;
     //...
     try{
         //...
         //app是ProcessRecord类型,app.thread是IApplicationThread类型
         //app.thread是应用进程的ApplicationThread在AMS的本地代理,前面已经讲过
         //所以这里实际调用的是ApplicationThread的scheduleLaunchActivity方法
         app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);
         //...
     }catch (RemoteException e) {
         //...
     }
     //...
     return true;
 }

app.thread是IApplicationThread类型,是ApplicationThread在AMS的本地代理,之后会通过IPC 调用到引用进程的ApplicationThread的scheduleLaunchActivity方法,如图,这样就又从服务端进程切换到了应用进程;

到这里Activity 前期的准备工作完成了,但要知道Activity 还没有创建呢。。。

从应用进程的startActivity 方法开始,会调用到ActivityManager.getService().startActivity() ,对应的是AMS 的startActivity 方法,这里进行了一次IPC ,在系统服务进程进行了一系列对于Activity 的处理,调用到app.thread.scheduleLaunchActivity() 对应的是ApplicationThread 的scheduleLaunchActivity() ,这里又进行了一次IPC ,回到应用进程,开始创建Activity ,回调Activity 的生命周期;过程简化如图:

由上图我们知道调用到了ApplicationThread 的scheduleLaunchActivity 方法;

private class ApplicationThread extends IApplicationThread.Stub {
       
        //...

        @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);
        }

        //...

}

可见由于系统服务处理完后传递的字段信息太多,为了方便传递,将这些封装到了ActivityClientRecord ,之后调用sendMessage 将ActivityClientRecord 发送了出去,继续追踪源码;

private void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

final H mH = new H();

private class H extends Handler {
    //...
}

可以看到H 就是一个Handler ,如果清楚Handler 机制,那就再好不过了,这样的话,接下来就去查看H 的 handleMessage 方法,对应的 H.LAUNCH_ACTIVITY 的处理就行了;可见系统源码都用的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;

            //...

        }
    }

从Handler H 对“LAUNCH_ACTIVITY”这个消息的处理可以知道,启动过程由handleLaunchActivity 方法实现;

handleLaunchActivity()

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

        Activity a = performLaunchActivity(r, customIntent);

        //...
    }

performLaunchActivity() 

// ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // ...

        // 1. 从ActivityClientRecord 里获取要启动的Activity 的组件信息
        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);
        }

        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            // 2. 通过Instrumentation 的 newActivity 方法使用类加载器创建Activity 对象
            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) {
            //...
        }

        try {
            // 3. 通过LoadedApk 的makeApplication 方法来尝试创建Application 对象
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            //..

            if (activity != null) {
                //...
                
                // 4. 通过Activity 的attach 方法来完成一些重要数据的初始化
                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, r.configCallback);

                //...
                
                // 5. 调用Activity 的onCreate 方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                
                //...
            }

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            //...
        }

        return activity;
    }

可以看到通过Instrumentation 的 newActivity 方法创建Activity 对象;

通过LoadedApk 的makeApplication 方法得到Application 对象,这里如果Application 已经创建过了,那么就不会再创建了,这也意味着一个应用只有一个Application 对象;

通过Activity 的attch 方法使ContextImpl 与Activity 关联起来,初次之外在attch 方法里Activity 还会完成Window 的创建,并与之关联,这样当Window 接收到外部输入事件后就可以将事件传递给Activity ;

通过Instrumentation 的 callActivityOnCreate 方法,调用Activity 的生命周期方法,onCreate 方法;

由于Activity 的onCreate 方法被调用,这也意味着Activity 的整个启动过程已完成。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值