2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Activity的启动过程(源码API27)

Activity的启动过程(源码API27)

时间:2023-02-05 02:33:14

相关推荐

Activity的启动过程(源码API27)

Oreo -> Android8.1 -> API level 27

启动activity的方式有以下几种:

1、在应用程序中startActivity()或startActivityForResult()启动指定activity2、在launcher中单击应用图标,启动新的activity3、按BACK键结束当前activity,自动启动上一个activity4、长按Home键,显示出当前任务列表,从中选择一个启动。

第2、3、4种方式最终都会走到第一种方式,startActivity()又会走到startActivityForResult()。

Launcher启动Activity

Zygote进程孵化出的第一个App进程是Launcher,这是用户看到的桌面App。我们打开LauncherActivity看下,其实也是通过intent来启动一个App。也就是说和第一种方式是一模一样的。

public abstract class LauncherActivity extends ListActivity {@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {Intent intent = intentForPosition(position);startActivity(intent);}}复制代码

Activity#startActivity()

@Overridepublic void startActivity(Intent intent) {this.startActivity(intent, null);}@Overridepublic void startActivity(Intent intent, @Nullable Bundle options) {if (options != null) {startActivityForResult(intent, -1, options);} else {// Note we want to go through this call for compatibility with// applications that may have overridden the method.startActivityForResult(intent, -1);}}复制代码

Activity#startActivityForResult()

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {startActivityForResult(intent, requestCode, null);}public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) {options = transferSpringboardActivityOptions(options);Instrumentation.ActivityResult ar =mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);if (ar != null) {mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(),ar.getResultData());}}复制代码

Instrumentation#execStartActivity()

mInstrumentation是一个Instrumentation对象,在Activity#attach()通过参数传递过来。mInstrumentation是在Application初始化的过程中实例化的。详情可以见Application的启动过程(源码)

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);public Instrumentation getInstrumentation() {return mInstrumentation;}复制代码

Instrumentation#execStartActivity()

ActivityManager.getService()通过Binder机制获得AMS的实例,然后跨进度调度AMS.startActivity()

public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,Intent intent, int requestCode, Bundle options) {IApplicationThread whoThread = (IApplicationThread) contextThread; //ApplicationThread对象try {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;}复制代码

ActivityManagerService#startActivity

@Overridepublic int startActivity(IBinder whoThread, String callingPackage,Intent intent, String resolvedType, Bundle bOptions) {appThread = IApplicationThread.Stub.asInterface(whoThread);return mActivityStarter.startActivityMayWait(appThread, -1, callingPackage, intent,resolvedType, null, null, null, null, 0, 0, null, null,null, bOptions, false, callingUser, tr, "AppTaskImpl");}复制代码

ActivityStarter#startActivityMayWait()

final int startActivityMayWait(IApplicationThread caller, int callingUid, xxxxx....) {final ActivityRecord[] outRecord = new ActivityRecord[1];int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor,resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,reason);return res;}}复制代码

ActivityStarter#startActivityLocked()

int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent, xxx.....) {mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,inTask);return mLastStartActivityResult != START_ABORTED ? mLastStartActivityResult : START_SUCCESS;}复制代码

ActivityStarter#startActivity()

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, TaskRecord inTask) {return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,options, inTask, outActivity);}复制代码

ActivityStarter#startAcitity()

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 {result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);} return result;}复制代码

ActivityStarter#startActivityUnchecked()

// Note: This method should only be called from {@link startActivity}.private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,mOptions);return START_SUCCESS;}复制代码

ActivityStack#startActivityLocked()

final void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,boolean newTask, boolean keepCurTransition, ActivityOptions options) {ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);}复制代码

ActivityStack#ensureActivitiesVisibleLocked()

final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,boolean preserveWindows) {if (r.app == null || r.app.thread == null) {if (makeVisibleAndRestartIfNeeded(starting, configChanges, isTop,resumeNextActivity, r)) {}} }复制代码

ActivityStack#makeVisibleAndRestartIfNeeded()

private boolean makeVisibleAndRestartIfNeeded(ActivityRecord starting, int configChanges,boolean isTop, boolean andResume, ActivityRecord r) {if (isTop || !r.visible) {if (r != starting) {mStackSupervisor.startSpecificActivityLocked(r, andResume, false);return true;}}return false;}复制代码

ActivityStackSupervisor#startSpecificActivityLocked()

这里兵分两路, if (app != null && app.thread != null) -> realStartActivityLocked() -> scheduleLaunchActivity,//app.thread是一个IApplicationThread对象,也就是说回调了ApplicationThread里的scheduleLaunchActivity

否则的话,mService.startProcessLocked(),mService是AMS对象,是在ActivityStackSupervisor构造函数里赋值的。

final ActivityManagerService mService;void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {ProcessRecord app = mService.getProcessRecordLocked(r.processName,r.info.applicationInfo.uid, true);if (app != null && app.thread != null) {try {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 {//app.thread是一个IApplicationThread对象,也就是说回调了ApplicationThread里的scheduleLaunchActivityapp.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,System.identityHashCode(r), r.info,// TODO: Have this take the merged configuration instead of separate global// and override configs.mergedConfiguration.getGlobalConfiguration(),mergedConfiguration.getOverrideConfiguration(), pat,r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,r.persistentState, results, newIntents, !andResume,mService.isNextTransitionForward(), profilerInfo);}复制代码

ActivityManagerService#startProcessLocked()

final ProcessRecord startProcessLocked(String processName,ApplicationInfo info, boolean knownToBeDead, int intentFlags,String hostingType, ComponentName hostingName, boolean allowWhileBooting,boolean isolated, boolean keepIfLarge) {return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,null /* crashHandler */);}复制代码

ActivityManagerService#startProcessLocked()

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {startProcessLocked(app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);return (app.pid != 0) ? app : null;}复制代码

ActivityManagerService#startProcessLocked()

private final void startProcessLocked(ProcessRecord app, String hostingType,String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {ProcessStartResult startResult;if (hostingType.equals("webview_service")) {startResult = startWebView(entryPoint,app.processName, uid, uid, gids, debugFlags, mountExternal,app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,app.info.dataDir, null, entryPointArgs);} else {startResult = Process.start(entryPoint,app.processName, uid, uid, gids, debugFlags, mountExternal,app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,app.info.dataDir, invokeWith, entryPointArgs);}}复制代码

Process#start()

public static final ProcessStartResult start(final String processClass,final String niceName,int uid, int gid, int[] gids,int debugFlags, int mountExternal,int targetSdkVersion,String seInfo,String abi,String instructionSet,String appDataDir,String invokeWith,String[] zygoteArgs) {return zygoteProcess.start(processClass, niceName, uid, gid, gids,debugFlags, mountExternal, targetSdkVersion, seInfo,abi, instructionSet, appDataDir, invokeWith, zygoteArgs);}复制代码

ZygoteProcess#start()

public final Process.ProcessStartResult start(final String processClass,final String niceName,int uid, int gid, int[] gids,int debugFlags, int mountExternal,int targetSdkVersion,String seInfo,String abi,String instructionSet,String appDataDir,String invokeWith,String[] zygoteArgs) {try {return startViaZygote(processClass, niceName, uid, gid, gids,debugFlags, mountExternal, targetSdkVersion, seInfo,abi, instructionSet, appDataDir, invokeWith, zygoteArgs);} catch (ZygoteStartFailedEx ex) {Log.e(LOG_TAG,"Starting VM process through Zygote failed");throw new RuntimeException("Starting VM process through Zygote failed", ex);}}复制代码

ZygoteProcess#startViaZygote()

private Process.ProcessStartResult startViaZygote(final String processClass,final String niceName,final int uid, final int gid,final int[] gids,int debugFlags, int mountExternal,int targetSdkVersion,String seInfo,String abi,String instructionSet,String appDataDir,String invokeWith,String[] extraArgs)throws ZygoteStartFailedEx {ArrayList<String> argsForZygote = new ArrayList<String>();// --runtime-args, --setuid=, --setgid=,// and --setgroups= must go firstargsForZygote.add("--runtime-args");argsForZygote.add("--setuid=" + uid);argsForZygote.add("--setgid=" + gid);//省略argsForZygote的各种参数配置synchronized(mLock) {return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);}}复制代码

ZygoteProcess#zygoteSendArgsAndGetResult()

启动一个新的进程

private static Process.ProcessStartResult zygoteSendArgsAndGetResult(ZygoteState zygoteState, ArrayList<String> args)throws ZygoteStartFailedEx {try {int sz = args.size();final BufferedWriter writer = zygoteState.writer;final DataInputStream inputStream = zygoteState.inputStream;writer.write(Integer.toString(args.size()));writer.newLine();for (int i = 0; i < sz; i++) {String arg = args.get(i);writer.write(arg);writer.newLine();}writer.flush();result.pid = inputStream.readInt();result.usingWrapper = inputStream.readBoolean();return result;} catch (IOException ex) {zygoteState.close();throw new ZygoteStartFailedEx(ex);}}复制代码

总结

Activity的启动是通过AMS来调度的,和application的启动过程类似,通过Binder机制和AMS通讯,Ams又回调IApplicationThread中的方法,由mH发出一个Message,并进行处理。

Process的启动是通过zygote来启动的。

中间的很多细节也没太研究。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。