C/C++教程

Activity源码学习总结

本文主要是介绍Activity源码学习总结,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Activity源码解析

lunchMode相关:https://zhuanlan.zhihu.com/p/265946165

activity的启动过程

  1. 根activity
  2. 普通activity

以下启动过程基于根activity:

ActivityManagerService负责四大组件的启动、切换、调度和进程的管理,是android的核心服务,参与了所有应用程序的启动管理。Activity的启动流程围绕AMS,可以大致分为3个部分:

  1. Launcher请求AMS的过程
  2. AMS到ApplicationThread的调用过程
  3. ActivityThread启动Activity的过程

Launcher请求AMS的过程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rv3gOK4J-1637650729538)(C:\Users\wangshuo\AppData\Roaming\Typora\typora-user-images\image-20210907175547815.png)]

桌面点击应用,调用launcher的startActivitySafely方法:

public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
    ...
    // Prepare intent
    // 样根Activity会在新的任务栈中启动
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ...
            // Could be launching some bookkeeping activity
        	// 最终调用startActivityForResult方法
            startActivity(intent, optsBundle);
    ...
}

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                                   @Nullable Bundle options) {
    // mParent为空,是当前activity的父类
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        // Instrumentation监控应用程序和系统的交互,并执行execStartActivity方法
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
            this, mMainThread.getApplicationThread(), mToken, this,
            intent, requestCode, options);
        ...
    } else {
        ...
    }
}

public ActivityResult execStartActivity(
    Context who, IBinder contextThread, IBinder token, Activity target,
    Intent intent, int requestCode, Bundle options) {
    ...
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            // 调用ActivityManager的getService方法来获取AMS的代理对象,再调用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;
}
//getService方法调用了IActivityManagerSingleton的get方法
public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
    new Singleton<IActivityManager>() {
    @Override
    protected IActivityManager create() {
        // IActivityManagerSingleton的get方法,会调用create方法,在注释1处得到IBinder类型的AMS引用
        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
        // 转换成IActivityManager类型的AMS代理对象
        //这段代码采用的是AIDL,IActivityManager.java类是由AIDL工具在编译时自动生成的。AMS继承IActivityManager.Stub类并实现相关方法。
        final IActivityManager am = IActivityManager.Stub.asInterface(b);
        return am;
    }
};

public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create();

    public final T get() {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            return mInstance;
        }
    }
}


一阶段具体流程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iUneJQV2-1637650729541)(C:\Users\wangshuo\AppData\Roaming\Typora\typora-user-images\image-20210908101817057.png)]

AMS到ApplicationThread的调用过程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FFAcEWlX-1637650729542)(C:\Users\wangshuo\AppData\Roaming\Typora\typora-user-images\image-20210908101956785.png)]

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) {
    //返回startActivityAsUser方法。startActivityAsUser方法比startActivity方法多了一个参数UserHandle.getCallingUserId(),这个方法会获得调用者的UserId,AMS根据这个UserId来确定调用者的权限。
	return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}

@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) {
    // 判断调用者进程是否被隔离----SecurityException
    enforceNotIsolatedCaller("startActivity");
    // 检查调用者的权限----SecurityException
    userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
             Binder.getCallingUid(),userId, false, ALLOW_FULL_ONLY, 
             "startActivity", null);
    // 调用了ActivityStarter的startActivityMayWait方法,参数要比startActivityAsUser多几个,需要注意的是倒数第二个参数类型为TaskRecord,代表启动的Activity所在的栈,最后一个参数"startActivityAsUser"代表启动的理由,接下来进入startActivityMayWait方法
	return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
	       resolvedType, null,null, resultTo, resultWho,requestCode,startFlags,
	       profilerInfo,null,null, bOptions, false, userId, null,
	       null,"startActivityAsUser");
}

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) {
	...
    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;
     }
}

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) {
	// 注释1
    // 判断启动
    if (TextUtils.isEmpty(reason)) {
    	throw new IllegalArgumentException("Need to specify a reason.");
    }
    ...
    mLastStartReason = reason;
    mLastStartActivityTimeMs = System.currentTimeMillis();
    mLastStartActivityRecord[0] = null;
	// 注释2
    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) {
        // mLastStartActivityRecord[0] is set in the call to startActivity above.
        outActivity[0] = mLastStartActivityRecord[0];
    }
    return mLastStartActivityResult;
}

/** DO NOT call this method directly. Use {@link #startActivityLocked} instead. */
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;
    // Pull the optional Ephemeral Installer-only bundle out of the options early.
    final Bundle verificationBundle
    	= options != null ? options.popAppVerificationBundle() : null;

    ProcessRecord callerApp = null;
    // 判断IApplicationThread类型的caller是否为null
    // caller为IApplicationThread类型
    if (caller != null) {
        // 得到Launcher进程
        callerApp = mService.getRecordForAppLocked(caller);
        if (callerApp != null) {
            // 获取Launcher进程的pid和uid
            callingPid = callerApp.pid;
            callingUid = callerApp.info.uid;
        } else {
            Slog.w(TAG, "Unable to find app for caller " + caller
                   + " (pid=" + callingPid + ") when starting: "
                   + intent.toString());
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }
    ...
    // 创建即将要启动的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) {
        // 创建的ActivityRecord赋值给ActivityRecord[]类型的outActivity
        outActivity[0] = r;
    }
    ...
    doPendingActivityLaunchesLocked(false);
    return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
    true,options, inTask, outActivity);
    }

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();
        // 注释1
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
             startFlags, doResume, options, inTask, outActivity);
    } 
    ...
    return result;
}

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {

    ...
        // 注释1
        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
            && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            newTask = true;
            // 注释2
            // 创建新的TaskRecord
            result = setTaskFromReuseOrCreateNewTask(
                taskToAffiliate, preferredLaunchStackId, topStack);
        } else if (mSourceRecord != null) {
            result = setTaskFromSourceRecord();
        } else if (mInTask != null) {
            result = setTaskFromInTask();
        } else {
            // This not being started from an existing activity, 
            // and not part of a new task...
            // just put it in the top task, though these days this case should never happen.
            setTaskToCurrentTopOrCreateNewTask();
        }
    ...

        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");
                }
                // 注释3
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack,mStartActivity,
                                                                mOptions);
            }
        } else {
            mTargetStack.addRecentActivityLocked(mStartActivity);
        }
    ...
}

boolean resumeFocusedStackTopActivityLocked(
    	ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions){
    if (targetStack != null && isFocusedStack(targetStack)) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    // 注释1
    // 获取要启动的Activity所在的栈的栈顶的不是处于停止状态的ActivityRecord
    final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
    // 注释2
    if (r == null || r.state != RESUMED) {
        // 注释3
        mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    } else if (r.state == RESUMED) {
        // Kick off any lingering app transitions form the MoveTaskToFront operation.
        mFocusedStack.executeAppTransition(targetOptions);
    }
    return false;
}

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mStackSupervisor.inResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        // Protect against recursion.
        mStackSupervisor.inResumeTopActivity = true;
        // 注释1
        result = resumeTopActivityInnerLocked(prev, options);
    } 
    ...
}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { 
    ...
        // 注释1
        mStackSupervisor.startSpecificActivityLocked(next, true, true);


    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    return true;
}

void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    // 注释1
    // 获取即将启动的Activity的所在的应用进程
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                        r.info.applicationInfo.uid, true);

    r.getStack().setLaunchTime(r);
	// 注释2
    // 判断要启动的Activity所在的应用程序进程如果已经运行的话,就会调用注释3处
    if (app != null && app.thread != null) {
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                || !"android".equals(r.info.packageName)) {

                app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                               mService.mProcessStats);
            }
            // 注释3
            // 这个方法第二个参数是代表要启动的Activity所在的应用程序进程的ProcessRecord
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                   + r.intent.getComponent().flattenToShortString(), e);
        }

        // If a dead object exception was thrown -- fall through to
        // restart the application.
    }

    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                                "activity", r.intent.getComponent(), false, false, true);
}


final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
      boolean andResume, boolean checkConfig) throws RemoteException {
    ...
    // 注释1
    // app是ProcessRecord类型的,thread是IApplicationThread类型的 
	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);
        ...
        return true;
}

注释1处的app.thread指的是IApplicationThread,其中ApplicationThread继承了IApplicationThread.Stub。app指的是传入的要启动的Activity所在的应用程序进程,因此这段代码指的就是要在目标应用程序进程启动Activity。当前代码逻辑运行在AMS所在的进程(SystemServer系统服务进程)中,通过ApplicationThread来与应用程序进程进程Binder通信(跨进程通信),也就是说ApplicationThread是AMS和应用程序进程的通信桥梁
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m7NaXz7b-1637650729544)(C:\Users\wangshuo\AppData\Roaming\Typora\typora-user-images\image-20210908112553954.png)]

ActivityThread启动Activity的过程

接着查看ApplicationThread的scheduleLaunchActivity方法,ApplicationThread是ActivityThread的内部类,ActivityThread负责管理当前应用程序进程的主线程

@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);
	// 此处的r就是保存要启动activity的信息,作为参数通过sendMessage发送出去
	ActivityClientRecord r = new ActivityClientRecord();

    r.token = token;
    r.ident = ident;
    r.intent = intent;
    r.referrer = referrer;
    ...
    updatePendingConfiguration(curConfig);
    sendMessage(H.LAUNCH_ACTIVITY, r);
}

sendMessage方法向H类发送类型为LAUNCH_ACTIVITY的消息,并将ActivityClientRecord传递出去

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

这里的mH指的是H,它是ActivityThread的内部类并继承Handler,是应用程序进程中主线程的消息管理类。因为ApplicationThread是一个Binder,它的调用逻辑运行在Binder线程池(子线程)中,所以这里需要用H将代码的逻辑切换到主线程中。

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");
            // 注释1
            // 取出之前保存的要启动的Activity的信息
            // 这些信息封装在ActivityClientRecord这个类中
            final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
			// 注释2
            // pachageinfo 指的是LoadedApk
            r.packageInfo = getPackageInfoNoCheck(
                r.activityInfo.applicationInfo, r.compatInfo);
            handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        } break;
        case RELAUNCH_ACTIVITY: {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
            ActivityClientRecord r = (ActivityClientRecord)msg.obj;
            handleRelaunchActivity(r);
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        } break;
        ...
    }
    ...
}


查看H类中handleMessage方法中对LAUNCH_ACTIVITY的处理,在注释1处将传过来的msg的成员变量obj转换为ActivityClientRecord。在注释2处通过getPackageInfoNoCheck方法获得LoadedApk类型的对象并赋值给ActivityClientRecord的成员变量packageInfo。应用程序要启动Activity时需要将该Activity所属的APK加载进来,而LoadedApk就是用来描述已加载的APK文件的。

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

    // Initialize before creating the activity
    WindowManagerGlobal.initialize();
	// 注释1
    // 启动Activity
    Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        Bundle oldState = r.state;
        // 注释2
        // 将Activity的状态置为Resume
        handleResumeActivity(r.token, false, r.isForward,
              !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

        if (!r.activity.mFinished && r.startsNotResumed) {

            performPauseActivityIfNeeded(r, reason);

            if (r.isPreHoneycomb()) {
                r.state = oldState;
            }
        }
    } else {
        // If there was an error, for any reason, tell the activity manager to stop us.
        try {
            // 注释3
            // 停止Activity启动
            ActivityManager.getService()
                .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
}

注释1处的performLaunchActivity方法用来启动Activity,注释2处的代码用来将Activity的状态设置为Resume,如果该Activity为null,就会执行注释3处的逻辑,通知AMS停止启动Activity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) 
    // 注释1 
    // 获取ActivityInfo类
    ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
    // 注释2 
    // 获取APK文件的描述类
    r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                                   Context.CONTEXT_INCLUDE_CODE);
}
// 注释3
// 获取要启动Activity的ComponentName类,它保存了该Activity的包名和类名
ComponentName component = r.intent.getComponent();
...
    // 注释4
    // 创建要启动Activity的上下文
    ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
    java.lang.ClassLoader cl = appContext.getClassLoader();
    // 注释5
    // 通过类加载器来创建要启动的Activity的实例
    activity = mInstrumentation.newActivity(
        cl, component.getClassName(), r.intent);
    ...
}
} catch (Exception e) {
    ...
}

try {
    // 注释6
    // 创建Application
    Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    ...
        if (activity != null) {
            ...
                // 注释7
                // 初始化Activity
                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);

            ...
                if (r.isPersistable()) {
                    // 注释8----展开调用
                    // 顾名思义下一步就是去调用Activity的onCreate方法
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
            ...
                r.paused = true;
            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            ...
        }
    return activity;
}

在注释1处获取ActivityInfo,用于存储代码以及AndroidManifest设置的Activity和Receiver节点信息,比如Activity的theme和launchMode。在注释2处获取APK文件的描述类LoadedApk。在注释3处获取要启动的Activity的ComponentName类,在该类中保存了Activity的包名和类名。注释4处用来创建要启动Activity的上下文环境。注释5处根据ComponentName中存储的Activity类名,用类加载器来创建该Activity的实例。注释6处用来创建Application,makeApplication方法内部会调用Application的onCreate方法。注释7处调用Activity的attach方法初始化Activity,在attach方法中会创建Window对象(PhoneWindow)并与Activity自身进行关联。

public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
}

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    restoreHasCurrentPermissionRequest(icicle);
    // 注释1
    // 正式进入Activity的生命周期方法
    onCreate(icicle, persistentState);
    mActivityTransitionState.readState(icicle);
    performCreateCommon();
}

Launcher—>AMS: Instrumentation主要用来监控应用程序和系统的交互,过渡调用它的execStartActivity方法,在该方法中获取AMS的代理对象,调用startActivity,即binder通信,跨进程进入AMS所在进程SystemServer,调用AMS的startActivity方法

AMS—>ApplicationThread: 这个过程涉及的类和方法相对较多,但主要完成下面三件事
①综合处理 launchMode 和 Intent 中的 Flag 标志位,并根据处理结果生成一个目标 Activity B 的对象(ActivityRecord)。
②判断是否需要为目标 Activity B 创建一个新的进程(ProcessRecord)、新的任务栈(TaskRecord)。
③获取ApplicationThread的代理对象,通过binder通信,跨进程到应用程序进程,去调用scheduleLaunchActivity去启动根Activity。

ActivityThread启动Activity的过程
onRequest(icicle);
// 注释1
// 正式进入Activity的生命周期方法
onCreate(icicle, persistentState);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}

Launcher—>AMS: Instrumentation主要用来监控应用程序和系统的交互,过渡调用它的execStartActivity方法,在该方法中获取AMS的代理对象,调用startActivity,即binder通信,跨进程进入AMS所在进程SystemServer,调用AMS的startActivity方法

AMS—>ApplicationThread: 这个过程涉及的类和方法相对较多,但主要完成下面三件事
①综合处理 launchMode 和 Intent 中的 Flag 标志位,并根据处理结果生成一个目标 Activity B 的对象(ActivityRecord)。
②判断是否需要为目标 Activity B 创建一个新的进程(ProcessRecord)、新的任务栈(TaskRecord)。
③获取ApplicationThread的代理对象,通过binder通信,跨进程到应用程序进程,去调用scheduleLaunchActivity去启动根Activity。

ActivityThread启动Activity的过程
scheduleLaunchActivity通过sendMessage向H类发送类型为LAUNCH_ACTIVITY的消息,H类的handleMessage方法,处理消息,调用ActivityThread的handleLaunchActivity,接着调用performLaunchActivity,又回到应用程序与系统交互的监控类Instrumentation,调用它的callActivityOnCreate方法,接着调用Activity的performCreate方法和onCreate方法,正式进入Activity的生命周期方法,启动Activity
这篇关于Activity源码学习总结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!