用户从Launcher程序点击应用图标可启动应用的入口Activity,Activity启动时需要多个进程之间的交互,Android系统中有一个zygote进程专用于孵化Android框架层和应用层程序的进程。还有一个system_server进程,该进程里运行了很多binder service,例如ActivityManagerService,PackageManagerService,WindowManagerService,这些binder service分别运行在不同的线程中,其中ActivityManagerService负责管理Activity栈,应用进程,task。
Activity启动时的概要交互流程如下图如下所示(点击图片可看 大图 ):
用户在Launcher程序里点击应用图标时,会通知ActivityManagerService启动应用的入口Activity,ActivityManagerService发现这个应用还未启动,则会通知Zygote进程孵化出应用进程,然后在这个dalvik应用进程里执行ActivityThread的main方法。应用进程接下来通知ActivityManagerService应用进程已启动,ActivityManagerService保存应用进程的一个代理对象,这样ActivityManagerService可以通过这个代理对象控制应用进程,然后ActivityManagerService通知应用进程创建入口Activity的实例,并执行它的生命周期方法。
后续博客将介绍Activity的详细启动流程。
在介绍Activity的详细启动流程之前,先为大家介绍Activity启动时涉及到的类,这样大家可以有大概的了解,不至于在细节中迷失。
Activity启动时涉及到的类有IActivityManager相关类, I ApplicationThread 相关类, ActivityManagerService 相关类。
点击图片可看 大图
Activity的管理采用binder机制,管理Activity的接口是IActivityManager. ActivityManagerService实现了Activity管理功能,位于system_server进程,ActivityManagerProxy对象是ActivityManagerService在普通应用进程的一个代理对象,应用进程通过ActivityManagerProxy对象调用ActivityManagerService提供的功能。应用进程并不会直接创建ActivityManagerProxy对象,而是通过调用ActiviyManagerNative类的工具方法getDefault方法得到ActivityManagerProxy对象。所以在应用进程里通常这样启动Activty:
ActivityManagerNative.getDefault().startActivity()
点击图片可看 大图
应用进程需要调用ActivityManagerService提供的功能,而ActivityManagerService也需要主动调用应用进程以控制应用进程并完成指定操作。这样ActivityManagerService也需要应用进程的一个Binder代理对象,而这个代理对象就是ApplicationThreadProxy对象。
ActivityManagerService通过IApplicationThread接口管理应用进程,ApplicationThread类实现了IApplicationThread接口,实现了管理应用的操作,ApplicationThread对象运行在应用进程里。ApplicationThreadProxy对象是ApplicationThread对象在ActivityManagerService线程 (ActivityManagerService线程运行在system_server进程)内的代理对象,ActivityManagerService通过ApplicationThreadProxy对象调用ApplicationThread提供的功能,比如让应用进程启动某个Activity。
点击图片可看 大图
ActivityManagerService管理Activity时,主要涉及以下几个类:
注意:
ActivityManagerService里只有一个ActivityStack对象,并不会像Android官方文档描述的一样,每个Task都有一个activity stack对象。ActivityStack管理ActivityRecord时,不是下面这样组织ActivityRecord的:
List<TaskRecord> taskList; //ActivityStack类 List<ActivityRecord> recordList;// TaskRecord类
而是像下面这样组织ActivityRecord:
ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>(); //ActivityStack类里 TaskRecord task; // ActivityRecord类里
也就是说ActivityManagerService组织回退栈时以ActivityRecord为基本单位,所有的ActivityRecord放在同一个ArrayList里,可以将mHistory看作一个栈对象,索引0所指的对象位于栈底,索引mHistory.size()-1所指的对象位于栈顶。
但是ActivityManagerService调度ActivityRecord时以task为基本单位,每个ActivityRecord对象都属于某个TaskRecord,一个TaskRecord可能有多个ActivityRecord。
ActivityStack没有TaskRecord列表的入口,只有在ActivityManagerService才有TaskRecord列表的入口:
final ArrayList<TaskRecord> mRecentTasks
ActivityStack管理ActivityRecord时,将属于同一个task的ActivityRecord放在一起,如下所示:
回退栈里可看到两个task,假设上面的task为task1,下面的task为task2,task1包含D,E两个Activity Record,task2包含3个ActivityRecord。task1位于回退栈的栈顶,task2位于task1下面,task1中E位于栈顶,task2中C位于栈顶。需注意两个task的Activity不会混在一起,也就是说task2的B不能放在task1的D和E中间。
因为回退栈是栈结构,所以此时不断按返回键,显示的Activity的顺序为E–>D–>C–>B–>A。
下一篇博客为大家讲述Activity的详细启动流程。
本篇博客将开始介绍Activity启动的详细流程,由于详细启动流程非常复杂,故此分成两篇来介绍。
本篇主要介绍前半部分的启动流程:
下篇介绍后半部分的启动流程:
点击图片可看 大图
在launcher应用程序里启动应用时,点击应用图标后,launcher程序会调用startActivity启动应用,传递的intent参数:
intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setComponent(className);
activity最终调用Instrumentation的execStartActivity来启动应用:
//Activity类 public void startActivityForResult(Intent intent, int requestCode, Bundle options) { if (mParent == null) { 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()); } //... }else{ //... }
Instrumentation调用ActivityManagerProxy对象的startActivity方法启动Activity,而ActivityManagerProxy只是ActivityManagerService对象在应用进程的一个代理对象,ActivityManagerProxy最终调用ActivityManagerService的startActvity方法启动Activity。
//Instrumentation类 public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { //... try{ //... int result = ActivityManagerNative.getDefault() .startActivity(whoThread, intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, null, options); } catch (RemoteException e) { } //... }
点击图片可看 大图
ActivityManagerProxy对象调用ActivityManagerService对象(运行在system_server进程)的startActivity方法以启动应用,startActivity方法接下来调用startActivityAsUser方法以启动应用。在startActivityAsUser方法里会调用ActivityStack的startActivityMayWait方法以启动应用,startActivityMayWait方法里启动应用时,需先根据intent在系统中找到合适的应用的activity,如果有多个activity可选择,则会弹出ResolverActivity让用户选择合适的应用。
//ActivityStack类 final int startActivityMayWait(IApplicationThread caller, int callingUid, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, String profileFile, ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config, Bundle options, int userId) { //… //根据intent在系统中找到合适的应用的activity,如果有多个activity可选择, //则会弹出ResolverActivity让用户选择合适的应用。 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profileFile, profileFd, userId); //… int res = startActivityLocked(caller, intent, resolvedType, aInfo, resultTo, resultWho, requestCode, callingPid, callingUid, startFlags, options, componentSpecified, null); //… }
在startActivityLocked方法里,对传过来的参数做一些校验,然后创建ActivityRecord对象,再调用startActivityUncheckedLocked方法启动Activity。
startActivityUncheckedLocked方法负责调度ActivityRecord和Task,理解该方法是理解Actvity启动模式的关键。
startActivityUncheckedLocked方法调度task的算法非常复杂,和当前回退栈,要启动的acitivity的启动模式以及taskAffinity属性,启动activity时设置的intent的flag等诸多要素相关,intent的flag就有很多种情况,故此算法非常复杂,需要阅读源码并结合特定启动情况才能理解。
后续会介绍startActivityUncheckedLocked方法的实现,并结合特定场景分析调度算法。
接下来调用startActivityLocked将ActivityRecord加入到回退栈里:
//ActivityStack类 final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord, int startFlags, boolean doResume, Bundle options) { //... startActivityLocked(r, newTask, doResume, keepCurTransition, options); //... }
在startActivityLocked里调用resumeTopActivityLocked显示栈顶Activity:
//ActivityStack类 private final void startActivityLocked(ActivityRecord r, boolean newTask, boolean doResume, boolean keepCurTransition, Bundle options) { //... if (doResume) { resumeTopActivityLocked(null); } }
resumeTopActivityLocked(null)会调用另一个resumeTopActivityLocked方法显示栈顶的acitivity:
//ActivityStack类 final boolean resumeTopActivityLocked(ActivityRecord prev) { return resumeTopActivityLocked(prev, null); }
因为应用还未启动过,所以调用startSpecificActivityLocked启动应用,执行逻辑如下:
//ActivityStack类 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { //... if (next.app != null && next.app.thread != null) { //… }else{ //… startSpecificActivityLocked(next, true, true); } //... }
在startSpecificActivityLocked里调用mService.startProcessLocked启动应用:
//ActivityStack类 private final void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid); //... mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false); }
在ActivityManagerService的startProcessLocked方法里:
//ActivityManagerService类 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, boolean allowWhileBooting, boolean isolated) { ProcessRecord app; if (!isolated) { app = getProcessRecordLocked(processName, info.uid); } else { //... } //... if (app == null) { app = newProcessRecordLocked(null, info, processName, isolated); if (app == null) { Slog.w(TAG, "Failed making new process record for " + processName + "/" + info.uid + " isolated=" + isolated); return null; } mProcessNames.put(processName, app.uid, app); if (isolated) { mIsolatedProcesses.put(app.uid, app); } } else { //.. } //... startProcessLocked(app, hostingType, hostingNameStr); //... }
在startProcessLocked方法里:
//ActivityManagerService类 private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr) { //... try { //... // Start the process. It will either succeed and return a result containing // the PID of the new process, or else throw a RuntimeException. //Zygote孵化dalvik应用进程后,会执行android.app.ActivityThread类的main方法 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread", app.processName, uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion, app.info.seinfo, null); //... } catch (RuntimeException e) { //... } }
在Process类的start方法里:
//Process类 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[] zygoteArgs) { try{ startViaZygote(processClass, niceName, uid, gid, gids, debugFlags, mountExternal, targetSdkVersion, seInfo, zygoteArgs); }catch (ZygoteStartFailedEx ex) { //... } }
在Process类的startViaZygote方法里,会计算启动应用进程用的各个参数,然后再调用zygoteSendArgsAndGetResult方法将这些参数通过socket发送给zygote进程,zygote进程会孵化出新的dalvik应用进程,然后告诉ActivityManagerService新启动的进程的pid。
点击图片可看 大图
zygote进程将ZygoteInit作为启动类,会执行它的main方法,先注册ZygoteSocket,然后调用runSelectLoop方法,runSelectLoop方法会调用方法在ZygoteSocket上监听请求,如果别的进程通过ZygoteSocket请求孵化进程,则孵化进程。
runSelectLoop方法的主要代码:
//ZygoteInit类 private static void runSelectLoopMode() throws MethodAndArgsCaller { //... while (true) { //... try { fdArray = fds.toArray(fdArray); index = selectReadable(fdArray); } catch (IOException ex) { throw new RuntimeException("Error in select()", ex); } if (index < 0) { throw new RuntimeException("Error in select()"); } else if (index == 0) { //监听客户连接请求 ZygoteConnection newPeer = acceptCommandPeer(); peers.add(newPeer); fds.add(newPeer.getFileDesciptor()); } else { //若客户发送孵化进程的请求过来, //此时便需要调用ZygoteConnection的runOnce方法孵化进程 boolean done; done = peers.get(index).runOnce(); if (done) { peers.remove(index); fds.remove(index); } } } }
在runOnce方法里调用Zygote.forkAndSpecialize方法孵化进程,如果返回值为0表示是在孵化出来的应用进程里,此时会调用handleChildProc进行一些处理,并使用异常机制进行逃逸,会直接逃逸至ZygoteInit的main方法。
//ZygoteConnection类 boolean runOnce() throws ZygoteInit.MethodAndArgsCaller { //... try { //... pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo, parsedArgs.niceName); } //... try { if (pid == 0) { // in child IoUtils.closeQuietly(serverPipeFd); serverPipeFd = null; //handleChildProc是一个很重要的函数,在该函数里使用了异常进行逃逸 handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr); //... } else { //... } } finally { //... } }
Zygote的forkAndSpecialize方法会调用nativeForkAndSpecialize方法孵化进程,nativeForkAndSpecialize是一个本地方法,它的实现在dalvik/vm/native/dalvik_system_Zygote.cpp里,在该cpp文件里与nativeForkAndSpecialize对应的C++方法是Dalvik_dalvik_system_Zygote_forkAndSpecialize,在该方法里会调用forkAndSpecializeCommon孵化进程,在forkAndSpecializeCommon方法里会调用fork系统调用创建进程,因为使用的是fork机制所以创建进程的效率比较高。
handleChildProc方法主要代码:
//ZygoteConnection类 private void handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr) throws ZygoteInit.MethodAndArgsCaller { //... if (parsedArgs.runtimeInit) { //... } else { String className; try { //这里得到的classname实际是android.app.ActivityThread className = parsedArgs.remainingArgs[0]; } catch (ArrayIndexOutOfBoundsException ex) { logAndPrintError(newStderr, "Missing required class name argument", null); return; } //... if (parsedArgs.invokeWith != null) { //... } else { ClassLoader cloader; if (parsedArgs.classpath != null) { cloader = new PathClassLoader(parsedArgs.classpath, ClassLoader.getSystemClassLoader()); } else { cloader = ClassLoader.getSystemClassLoader(); } //调用ZygoteInit.invokeStaticMain执行android.app.ActivityThread的main方法 try { ZygoteInit.invokeStaticMain(cloader, className, mainArgs); } catch (RuntimeException ex) { logAndPrintError(newStderr, "Error starting.", ex); } } } }
ZygoteInit的invokeStaticMain方法并不会直接执行className的main方法,而是会构造一个 ZygoteInit.MethodAndArgsCaller异常,然后抛出来,通过异常机制会直接跳转到ZygoteInit的main方法, ZygoteInit.MethodAndArgsCaller类实现了Runnable方法,在run方法里会执行要求执行的main方法,故此跳转到ZygoteInit的main方法后,异常会被捕获,然后执行方法caller.run(),这样便会执行android.app.ActivityThread的main方法。
ZygoteInit的invokeStaticMain方法主要代码:
//ZygoteInit类 static void invokeStaticMain(ClassLoader loader, String className, String[] argv) throws ZygoteInit.MethodAndArgsCaller { //... Method m; try { m = cl.getMethod("main", new Class[] { String[].class }); } catch(//...){ } //... throw new ZygoteInit.MethodAndArgsCaller(m, argv); }
ZygoteInit.MethodAndArgsCaller主要代码:
public static class MethodAndArgsCaller extends Exception implements Runnable { //... public void run() { try { mMethod.invoke(null, new Object[] { mArgs }); }//... } }
ZygoteInit的main方法相关代码:
//ZygoteInit类 public static void main(String argv[]) { try { //... } catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { //... } }
下面博客将介绍Activity详细启动流程的后半部分。
上篇博客介绍了Activity详细启动流程的前半部分:
本篇博客主要介绍Activity详细启动流程的后半部分:
点击图片可看 大图
Zygote进程孵化出新的应用进程后,会执行ActivityThread类的main方法。在该方法里会先准备好Looper和消息队列,然后调用attach方法将应用进程绑定到ActivityManagerService,然后进入loop循环,不断地读取消息队列里的消息,并分发消息。
//ActivityThread类 public static void main(String[] args) { //... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } AsyncTask.init(); //... Looper.loop(); //... }
点击图片可看 大图
在ActivityThread的main方法里调用thread.attach(false);attach方法的主要代码如下所示:
//ActivityThread类 private void attach(boolean system) { sThreadLocal.set(this); mSystemThread = system; if (!system) { //... IActivityManager mgr = ActivityManagerNative.getDefault(); try { //调用ActivityManagerService的attachApplication方法 //将ApplicationThread对象绑定至ActivityManagerService, //这样ActivityManagerService就可以 //通过ApplicationThread代理对象控制应用进程 mgr.attachApplication(mAppThread); } catch (RemoteException ex) { // Ignore } } else { //... } //... }
ActivityManagerService的attachApplication方法执行attachApplicationLocked(thread, callingPid)进行绑定。
//ActivityManagerService类 private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { ProcessRecord app; //... app.thread = thread; //... try { //... thread.bindApplication(processName, appInfo, providers, app.instrumentationClass, profileFile, profileFd, profileAutoStop, app.instrumentationArguments, app.instrumentationWatcher, testMode, enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), mCoreSettingsObserver.getCoreSettingsLocked()); //... } catch (Exception e) { //... } //... ActivityRecord hr = mMainStack.topRunningActivityLocked(null); if (hr != null && normalMode) { if (hr.app == null && app.uid == hr.info.applicationInfo.uid && processName.equals(hr.processName)) { try { if (mHeadless) { Slog.e(TAG, "Starting activities not supported on headless device: " + hr); } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) { //mMainStack.realStartActivityLocked真正启动activity didSomething = true; } } catch (Exception e) { //... } } else { //... } } //... return true; }
attachApplicationLocked方法有两个重要的函数调用thread.bindApplication和mMainStack.realStartActivityLocked。thread.bindApplication将应用进程的ApplicationThread对象绑定到ActivityManagerService,也就是说获得ApplicationThread对象的代理对象。mMainStack.realStartActivityLocked通知应用进程启动Activity。
thread对象其实是ActivityThread里ApplicationThread对象在ActivityManagerService的代理对象,故此执行thread.bindApplication,最终会调用ApplicationThread的bindApplication方法,该方法的主要代码如下所示:
//ActivityThread类 public final void bindApplication(String processName, ApplicationInfo appInfo, List<ProviderInfo> providers, ComponentName instrumentationName, String profileFile, ParcelFileDescriptor profileFd, boolean autoStopProfiler, Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher, int debugMode, boolean enableOpenGlTrace, boolean isRestrictedBackupMode, boolean persistent, Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) { //... AppBindData data = new AppBindData(); data.processName = processName; data.appInfo = appInfo; data.providers = providers; data.instrumentationName = instrumentationName; data.instrumentationArgs = instrumentationArgs; data.instrumentationWatcher = instrumentationWatcher; data.debugMode = debugMode; data.enableOpenGlTrace = enableOpenGlTrace; data.restrictedBackupMode = isRestrictedBackupMode; data.persistent = persistent; data.config = config; data.compatInfo = compatInfo; data.initProfileFile = profileFile; data.initProfileFd = profileFd; data.initAutoStopProfiler = false; queueOrSendMessage(H.BIND_APPLICATION, data); }
这样调用queueOrSendMessage会往ActivityThread的消息队列发送消息,消息的用途是BIND_APPLICATION。
这样会在handler里处理BIND_APPLICATION消息,接着调用handleBindApplication方法处理绑定消息。
//ActivityThread类 private void handleBindApplication(AppBindData data) { //... ApplicationInfo instrApp = new ApplicationInfo(); instrApp.packageName = ii.packageName; instrApp.sourceDir = ii.sourceDir; instrApp.publicSourceDir = ii.publicSourceDir; instrApp.dataDir = ii.dataDir; instrApp.nativeLibraryDir = ii.nativeLibraryDir; LoadedApk pi = getPackageInfo(instrApp, data.compatInfo, appContext.getClassLoader(), false, true); ContextImpl instrContext = new ContextImpl(); instrContext.init(pi, null, this); //... if (data.instrumentationName != null) { //... } else { //注意Activity的所有生命周期方法都会被Instrumentation对象所监控, //也就说执行Activity的生命周期方法前后一定会调用Instrumentation对象的相关方法 //并不是说只有跑单测用例才会建立Instrumentation对象, //即使不跑单测也会建立Instrumentation对象 mInstrumentation = new Instrumentation(); } //... try { //... Application app = data.info.makeApplication(data.restrictedBackupMode, null); mInitialApplication = app; //... try { mInstrumentation.onCreate(data.instrumentationArgs); }catch (Exception e) { //... } try { //这里会调用Application的onCreate方法 //故此Applcation对象的onCreate方法会比ActivityThread的main方法后调用 //但是会比这个应用的所有activity先调用 mInstrumentation.callApplicationOnCreate(app); } catch (Exception e) { //... } } finally { StrictMode.setThreadPolicy(savedPolicy); } }
realStartActivity会调用scheduleLaunchActivity启动activity,主要代码:
//ActivityStack类 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { //... try { //... app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), r.compat, r.icicle, results, newIntents, !andResume, mService.isNextTransitionForward(), profileFile, profileFd, profileAutoStop); //... } catch (RemoteException e) { //... } //... return true; }
同样app.thread也只是ApplicationThread对象在ActivityManagerService的一个代理对象而已,最终会调用ApplicationThread的scheduleLaunchActivity方法。
//ActivityThread类 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo, Bundle state, List<ResultInfo> pendingResults, List<Intent> pendingNewIntents, boolean notResumed, boolean isForward, String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) { ActivityClientRecord r = new ActivityClientRecord(); r.token = token; r.ident = ident; r.intent = intent; r.activityInfo = info; r.compatInfo = compatInfo; r.state = state; r.pendingResults = pendingResults; r.pendingIntents = pendingNewIntents; r.startsNotResumed = notResumed; r.isForward = isForward; r.profileFile = profileName; r.profileFd = profileFd; r.autoStopProfiler = autoStopProfiler; updatePendingConfiguration(curConfig); queueOrSendMessage(H.LAUNCH_ACTIVITY, r); }
这里调用了queueOrSendMessage往ActivityThread的消息队列发送了消息,消息的用途是启动Activity,接下来ActivityThread的handler便会处理该消息。
点击图片可看 大图
ActivityThread的handler调用handleLaunchActivity处理启动Activity的消息,handleLaunchActivity的主要代码如下所示:
//ActivityThread类 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) { //... Activity a = performLaunchActivity(r, customIntent); if (a != null) { //... handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed); //... } else { //... } }
handleLaunchActivity方法里有有两个重要的函数调用,performLaunchActivity和handleResumeActivity,performLaunchActivity会调用Activity的onCreate,onStart,onResotreInstanceState方法,handleResumeActivity会调用Activity的onResume方法.
performLaunchActivity的主要代码如下所示:
//ActivityThread类 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { //... Activity activity = null; try { java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); //... } catch (Exception e) { //... } try { //r.packageInfo.makeApplication实际并未创建Application对象, //因为bindApplication过程已经创建了Application对象, //makeApplication方法会返回已创建的Application对象 Application app = r.packageInfo.makeApplication(false, mInstrumentation); //... if (activity != null) { //... //将application对象,appContext对象绑定到新建的activity对象 activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo, title, r.parent, r.embeddedID, r.lastNonConfigurationInstances, config); //... //会调用Activity的onCreate方法 mInstrumentation.callActivityOnCreate(activity, r.state); //... //... //调用Activity的onStart方法 if (!r.activity.mFinished) { activity.performStart(); r.stopped = false; } if (!r.activity.mFinished) { if (r.state != null) { //会调用Activity的onRestoreInstanceState方法 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state); } } if (!r.activity.mFinished) { activity.mCalled = false; mInstrumentation.callActivityOnPostCreate(activity, r.state); //... } } //... } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { //... } return activity; }
handleResumeActivity的主要代码如下所示:
//ActivityThread类 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume) { //... //performResumeActivity最终会调用Activity的onResume方法 ActivityClientRecord r = performResumeActivity(token, clearHide); if (r != null) { final Activity a = r.activity; //... //显示界面 if (r.window == null && !a.mFinished && willBeVisible) { r.window = r.activity.getWindow(); View decor = r.window.getDecorView(); decor.setVisibility(View.INVISIBLE); ViewManager wm = a.getWindowManager(); WindowManager.LayoutParams l = r.window.getAttributes(); a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; if (a.mVisibleFromClient) { a.mWindowAdded = true; wm.addView(decor, l); } //... } else if (!willBeVisible) { //... } // Tell the activity manager we have resumed. if (reallyResume) { try { ActivityManagerNative.getDefault().activityResumed(token); } catch (RemoteException ex) { } } } else { //... } }
performResumeActivity的主要代码如下所示:
//ActivityThread类 public final ActivityClientRecord performResumeActivity(IBinder token, boolean clearHide) { ActivityClientRecord r = mActivities.get(token); //... if (r != null && !r.activity.mFinished) { //... try { //... //会调用Activity的onResume方法 r.activity.performResume(); //... } catch (Exception e) { //... } } return r; }
Activity的概要启动流程:
用户在Launcher程序里点击应用图标时,会通知ActivityManagerService启动应用的入口Activity,ActivityManagerService发现这个应用还未启动,则会通知Zygote进程孵化出应用进程,然后在这个dalvik应用进程里执行ActivityThread的main方法。应用进程接下来通知ActivityManagerService应用进程已启动,ActivityManagerService保存应用进程的一个代理对象,这样ActivityManagerService可以通过这个代理对象控制应用进程,然后ActivityManagerService通知应用进程创建入口Activity的实例,并执行它的生命周期方法
现在也可以理解:
如果应用的组件(包括所有组件Activity,Service,ContentProvider,Receiver) 被启动,肯定会先启动以应用包名为进程名的进程,这些组件都会运行在应用包名为进程名的进程里,并且是在主线程里。应用进程启动时会先创建Application对象,并执行Application对象的生命周期方法,然后才启动应用的组件。
有一种情况比较特殊,那就是为组件设置了特殊的进程名,也就是说通过android:process设置进程名的情况,此时组件运行在单独的进程内。
下篇博客将介绍Activity,Task的调度算法。
前面两篇博客介绍了Activity的详细启动流程,提到ActivityStack类的startActivityUncheckedLocked方法负责调度ActivityRecord和Task,并且调度算法非常复杂,需结合实际场景分析调度算法。本篇博客将介绍startActivityUncheckedLocked方法的具体实现,本结合实际场景分析调度算法。
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, int startFlags, boolean doResume,
Bundle options) {
//...
//如果从Launcher程序启动应用,launchFlags为
//FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
//否则一般情况下launcheFlags为0,除非启动Activity时设置了特殊的flag
int launchFlags = intent.getFlags();
//启动Activity时默认不会设置FLAG_ACTIVITY_PREVIOUS_IS_TOP
//故此notTop默认情况下会是null
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
//默认情况下startFlags不会设置START_FLAG_ONLY_IF_NEEDED
// If the onlyIfNeeded flag is set, then we can do this if the activity
// being launched is the same as the one making the call... or, as
// a special case, if we do not know the caller then we count the
// current top activity as the caller.
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
//...默认情况下这里的代码不会执行
}
//根据被启动的Activity和sourceRecord设置标志
//launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK
//如果从通知栏启动应用 sourceRecord == null
if (sourceRecord == null) {
// This activity is not being started from another... in this
// case we -always- start a new task.
if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
Slog.w(TAG, "startActivity called from non-Activity context;"
+"forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
+ intent);
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
}
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// The original activity who is starting us is running as a single
// instance... this new activity it is starting must go on its
// own task.
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
// The activity being started is a single instance... it always
// gets launched into its own task.
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
}
//一般情况下r.resultTo 不为null,它是启动该Activity的Activity,
//如果从通知栏启动Activity 则r.result为null
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//...
r.resultTo = null;
}
//addingToTask 如果为true表示正在添加至某个task,
// 后续需要将r添加至sourceRecord所在的task
boolean addingToTask = false;
//movedHome表示是否移动home task
boolean movedHome = false;
//reuseTask 如果不为null,则表示已存在task,会重用这个task,
// 但是这个Task里的所有Activity会被清除掉,
// 需要将r加入这个task
TaskRecord reuseTask = null;
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//从通知栏启动时r.resultTo == null
//如果launchFlags设置了FLAG_ACTIVITY_NEW_TASK,r.resultTo也会为null
if (r.resultTo == null) {
//查找ActivityRecord栈,看要启动的activity是否已有相关task,
//如果已经有相关task,则不需要创建新的task,可以使用已有的task
//如果要启动的activity的启动模式是LAUNCH_SINGLE_INSTANCE,
//则使用快速查找方法findTaskLocked,否则使用慢速查找方法findActivityLocked
//因为如果启动模式是LAUNCH_SINGLE_INSTANCE,则这个activity只会在一个单独的Task里
//故此查找时,可以以task为单位进行查找和比较,这样比较快
//查找得到的结果taskTop是相关task的栈顶的ActivityRecord
// See if there is a task to bring to the front. If this is
// a SINGLE_INSTANCE activity, there can be one and only one
// instance of it in the history, and it is always in its own
// unique task, so we do a special search.
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
//找到了相关task
if (taskTop != null) {
//重设task的intent
if (taskTop.task.intent == null) {
// This task was started because of movement of
// the activity based on affinity... now that we
// are actually launching it, we can assign the
// base intent.
taskTop.task.setIntent(intent, r.info);
}
//如果目标task不在栈顶,
//则先将Home task移动到栈顶(实际上只有当启动Activity设置的Flag同时设置了
//FLAG_ACTIVITY_TASK_ON_HOME和FLAG_ACTIVITY_NEW_TASK才会移动home task,
//否则不会移动home task),
//然后再将目标task移动到栈顶
// If the target task is not in the front, then we need
// to bring it to the front... except... well, with
// SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
// to have the same behavior as if a new instance was
// being started, which means not bringing it to the front
// if the caller is not itself in the front.
ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
if (curTop != null && curTop.task != taskTop.task) {
r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
boolean callerAtFront = sourceRecord == null
|| curTop.task == sourceRecord.task;
if (callerAtFront) {
// We really do want to push this one into the
// user's face, right now.
movedHome = true;
moveHomeToFrontFromLaunchLocked(launchFlags);
moveTaskToFrontLocked(taskTop.task, r, options);
options = null;
}
}
//如果launchFlags设置了FLAG_ACTIVITY_RESET_TASK_IF_NEEDED,则会重置task
//从Launcher应用程序启动应用会设置FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
// If the caller has requested that the target task be
// reset, then do so.
if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
taskTop = resetTaskIfNeededLocked(taskTop, r);
}
//... 一般情况下startFlags 不会设置 START_FLAG_ONLY_IF_NEEDED
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
//...
}
// ==================================
//默认情况下不会设置 Intent.FLAG_ACTIVITY_CLEAR_TASK
if ((launchFlags &
(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
== (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
// The caller has requested to completely replace any
// existing task with its new activity. Well that should
// not be too hard...
reuseTask = taskTop.task;
performClearTaskLocked(taskTop.task.taskId);
reuseTask.setIntent(r.intent, r.info);
} else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//默认情况下launchFlags不会设置FLAG_ACTIVITY_CLEAR_TOP
//但是如果被启动的activity的启动模式是singleTask或者singleInstance,
//也会进入该分支
// In this situation we want to remove all activities
// from the task up to the one being started. In most
// cases this means we are resetting the task to its
// initial state.
//清除r所在的task 在r之上的所有activity,
//该task里r和在r下的activity不会被清除
ActivityRecord top = performClearTaskLocked(
taskTop.task.taskId, r, launchFlags);
if (top != null) {
if (top.frontOfTask) {
// Activity aliases may mean we use different
// intents for the top activity, so make sure
// the task now has the identity of the new
// intent.
top.task.setIntent(r.intent, r.info);
}
logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
top.deliverNewIntentLocked(callingUid, r.intent);
} else {
// A special case: we need to
// start the activity because it is not currently
// running, and the caller has asked to clear the
// current task to have this activity at the top.
addingToTask = true;
// Now pretend like this activity is being started
// by the top of its task, so it is put in the
// right place.
sourceRecord = taskTop;
}
} else if (r.realActivity.equals(taskTop.task.realActivity)) {
// In this case the top activity on the task is the
// same as the one being launched, so we take that
// as a request to bring the task to the foreground.
// If the top activity in the task is the root
// activity, deliver this new intent to it if it
// desires.
if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
&& taskTop.realActivity.equals(r.realActivity)) {
logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
if (taskTop.frontOfTask) {
taskTop.task.setIntent(r.intent, r.info);
}
taskTop.deliverNewIntentLocked(callingUid, r.intent);
} else if (!r.intent.filterEquals(taskTop.task.intent)) {
// In this case we are launching the root activity
// of the task, but with a different intent. We
// should start a new instance on top.
addingToTask = true;
sourceRecord = taskTop;
}
} else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
// In this case an activity is being launched in to an
// existing task, without resetting that task. This
// is typically the situation of launching an activity
// from a notification or shortcut. We want to place
// the new activity on top of the current task.
addingToTask = true;
sourceRecord = taskTop;
} else if (!taskTop.task.rootWasReset) {
//进入该分支的情况比较少
// In this case we are launching in to an existing task
// that has not yet been started from its front door.
// The current task has been brought to the front.
// Ideally, we'd probably like to place this new task
// at the bottom of its stack, but that's a little hard
// to do with the current organization of the code so
// for now we'll just drop it.
taskTop.task.setIntent(r.intent, r.info);
}
// ================================== end
//如果没有正在添加至某个Task, 并且不用加入一个已清除所有Activity的Task
//此时只需要显示栈顶Activity即可
if (!addingToTask && reuseTask == null) {
// We didn't do anything... but it was needed (a.k.a., client
// don't use that intent!) And for paranoia, make
// sure we have correctly resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null, options);
} else {
ActivityOptions.abort(options);
}
return ActivityManager.START_TASK_TO_FRONT;
}
}
}
}
//...
if (r.packageName != null) {
// If the activity being launched is the same as the one currently
// at the top, then we need to check if it should only be launched
// once.
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
if (top.app != null && top.app.thread != null) {
if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
//singleTop启动模式或者singleTask启动模式,
//并且task栈顶的activity是要启动的activity,则先显示Activity
//然后调用该Activity的onNewIntent方法
logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
// For paranoia, make sure we have correctly
// resumed the top activity.
//先显示Activity
if (doResume) {
resumeTopActivityLocked(null);
}
ActivityOptions.abort(options);
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
// We don't need to start a new activity, and
// the client said not to do anything if that
// is the case, so this is it!
return ActivityManager.START_RETURN_INTENT_TO_CALLER;
}
//然后调用已显示activity的onNewIntent方法
top.deliverNewIntentLocked(callingUid, r.intent);
return ActivityManager.START_DELIVERED_TO_TOP;
}
}
}
}
} else {
if (r.resultTo != null) {
sendActivityResultLocked(-1,
r.resultTo, r.resultWho, r.requestCode,
Activity.RESULT_CANCELED, null);
}
ActivityOptions.abort(options);
return ActivityManager.START_CLASS_NOT_FOUND;
}
boolean newTask = false;
boolean keepCurTransition = false;
// Should this be considered a new task?
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
if (reuseTask == null) {
//创建新的task
// todo: should do better management of integers.
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in new task " + r.task);
} else {
//重复利用先前的task,该task里的所有acitivity已经被清空
r.setTask(reuseTask, reuseTask, true);
}
newTask = true;
if (!movedHome) {
moveHomeToFrontFromLaunchLocked(launchFlags);
}
} else if (sourceRecord != null) {
if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
// In this case, we are adding the activity to an existing
// task, but the caller has asked to clear that task if the
// activity is already running.
//清除r所在task在r之上的所有task,如果r不在task里,则返回的top为null
ActivityRecord top = performClearTaskLocked(
sourceRecord.task.taskId, r, launchFlags);
keepCurTransition = true;
if (top != null) {
logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
//先调用onNewIntent方法 然后再显示
top.deliverNewIntentLocked(callingUid, r.intent);
// For paranoia, make sure we have correctly
// resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null);
}
ActivityOptions.abort(options);
return ActivityManager.START_DELIVERED_TO_TOP;
}
} else if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
//将栈里已有的activity移到栈顶
// In this case, we are launching an activity in our own task
// that may already be running somewhere in the history, and
// we want to shuffle it to the front of the stack if so.
int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
if (where >= 0) {
ActivityRecord top = moveActivityToFrontLocked(where);
logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
top.updateOptionsLocked(options);
top.deliverNewIntentLocked(callingUid, r.intent);
if (doResume) {
resumeTopActivityLocked(null);
}
return ActivityManager.START_DELIVERED_TO_TOP;
}
}
// An existing activity is starting this new activity, so we want
// to keep the new one in the same task as the one that is starting
// it.
//同一个应用程序里的Activity A和Activity B,A可跳转至B,没有设置taskAffinity
//B的启动模式为singleTask,从A跳转至B时,B和A会在同一个task里
//该情况下会执行到这里的代码,将B的task设置为和A一样的task
r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in existing task " + r.task);
} 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.
final int N = mHistory.size();
ActivityRecord prev =
N > 0 ? mHistory.get(N-1) : null;
r.setTask(prev != null
? prev.task
: new TaskRecord(mService.mCurTask, r.info, intent), null, true);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in new guessed " + r.task);
}
mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
intent, r.getUriPermissionsLocked());
if (newTask) {
EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
}
logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
startActivityLocked(r, newTask, doResume, keepCurTransition, options);
return ActivityManager.START_SUCCESS;
}
实际场景1:
应用内有两个Activity,A和B,A为第应用入口Activity,从A可跳转至B,A和B的启动模式都为standard
1)从Launcher程序第1次启动应用时的任务调度情况:
任务调度时会创建新task并将新的ActivityRecord加入这个新的task
2)然后跳转至应用内Activity时的任务调度情况:
任务调度时会将新的ActivityRecord加入已有的task
3)然后按Home键,再打开应用程序时的调度情况:
任务调度时会先找到已有的相关task,并显示栈顶的Activity
1)从Launcher程序第1次启动应用时
会创建新task并将新的ActivityRecord加入这个新的task,任务调度执行如下所示:
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, int startFlags, boolean doResume,
Bundle options) {
//...
//launchFlags为FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
int launchFlags = intent.getFlags();
//...
//没设置FLAG_ACTIVITY_PREVIOUS_IS_TOP,故此notTop为null
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
//startFlags未设置ActivityManager.START_FLAG_ONLY_IF_NEEDED
//...
//sourceRecord为Launcher应用的Activity launcher应用activity的启动模式为singleTask
// 故此下面的3个条件分支的内容都不会执行
if (sourceRecord == null) {
//...
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//...
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
//...
}
//...
//r.resultTo不为null, launchFlags设置了FLAG_ACTIVITY_NEW_TASK,需要将r.resultTo置为null
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//...
r.resultTo = null;
}
boolean addingToTask = false;
boolean movedHome = false;
TaskRecord reuseTask = null;
//因为launchFlags为FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
//故此下面的条件会满足, 也就是说只要从Launcher程序启动应用,下面这个条件肯定会满足
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//...
if (r.resultTo == null) {
//因为应用被第一次启动,故此找不到相关task,taskTop则为null
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
if (taskTop != null) {
//... 这里面的内容不会执行
}
}
}
//...
//r.packageName != null
if (r.packageName != null) {
//如果被启动的Activity正好是栈顶的Activity,
//并且被启动的Activity启动模式是singleTop或者singleTask,
//则不用将新的ActivityRecord加入到栈里
//top Activity为Launcher应用的Activity
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
//top.realActivity.equals(r.realActivity)不满足
if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
//... 这里的代码不会被执行
}
}
} else {
//...
}
boolean newTask = false;
boolean keepCurTransition = false;
// 此时 r.resultTo为null addingToTask为false launchFlags设置了FLAG_ACTIVITY_NEW_TASK
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
if (reuseTask == null) {
// todo: should do better management of integers.
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
//创建新task
r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
+ " in new task " + r.task);
} else {
//...这里的代码会执行
}
newTask = true;
if (!movedHome) {
moveHomeToFrontFromLaunchLocked(launchFlags);
}
} else if (sourceRecord != null) {
//... 这里的代码不会被执行
} else {
//...这里的代码不会被执行
}
//...
startActivityLocked(r, newTask, doResume, keepCurTransition, options);
return ActivityManager.START_SUCCESS;
}
2)跳转至应用内Activity时
会将新的ActivityRecord加入已有的task,任务调度执行如下所示:
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, int startFlags, boolean doResume,
Bundle options) {
//此时launchFlags为0
int launchFlags = intent.getFlags();
//notTop为null
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
//startFlags未设置ActivityManager.START_FLAG_ONLY_IF_NEEDED
//...
if (sourceRecord == null) {
//...这里的代码不会被执行
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//...这里的代码不会被执行
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
//...这里的代码不会被执行
}
//r.resultTo != null 但是launchFlags未设置FLAG_ACTIVITY_NEW_TASK
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//... 这里的代码不执行
}
boolean addingToTask = false;
boolean movedHome = false;
TaskRecord reuseTask = null;
//launchFlags为0 r的启动模式为standard 故此下面的逻辑都不会执行
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//... 这里的代码不执行
}
//...
if (r.packageName != null) {
//top 是ActivityA 的ActivityRecord,
//但是被启动的Activity和top不是同一个Activity
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
//...这里的代码不执行
}
}
} else {
//...这里的代码不执行
}
boolean newTask = false;
boolean keepCurTransition = false;
//此时 r.resultTo !=null sourceRecord != null addingToTask=false
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//...这里的代码不执行
} else if (sourceRecord != null) {
if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
//... 这里的代码不执行
} else if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
//... 这里的代码不执行
}
//添加到现有的task
r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
//...
} else {
//... 这里的代码不执行
}
//...
return ActivityManager.START_SUCCESS;
}
3)然后按Home键,再打开应用程序
此时会先找到已有的相关task,并显示栈顶的Activity,任务调度执行如下所示:
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, int startFlags, boolean doResume,
Bundle options) {
//...
//launchFlags为FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
int launchFlags = intent.getFlags();
//notTop为null
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
//startFlags未设置ActivityManager.START_FLAG_ONLY_IF_NEEDED
//...
if (sourceRecord == null) {
//...这里的代码不会被执行
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//...这里的代码不会被执行
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
//...这里的代码不会被执行
}
//此时 r.resultTo != null launchFlags设置了FLAG_ACTIVITY_NEW_TASK
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//...
r.resultTo = null;
}
boolean addingToTask = false;
boolean movedHome = false;
TaskRecord reuseTask = null;
//此时launchFlags设置了FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//此时 r.resultTo == null
if (r.resultTo == null) {
//此时已有相关task,并且task 栈的栈顶是Activity B的ActivityRecord
//故此taskTop为Activity B的ActivityRecord
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
if (taskTop != null) {
//...
// 此时curTop是Launcher应用的Activity的ActivityRecord
ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
if (curTop != null && curTop.task != taskTop.task) {
r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
//此时Launcher应用的task在栈顶,故此callerAtFront为true,
//此时会把被启动的应用的task移至栈顶
boolean callerAtFront = sourceRecord == null
|| curTop.task == sourceRecord.task;
if (callerAtFront) {
// We really do want to push this one into the
// user's face, right now.
movedHome = true;
moveHomeToFrontFromLaunchLocked(launchFlags);
moveTaskToFrontLocked(taskTop.task, r, options);
options = null;
}
}
//此时launchFlags设置了FLAG_ACTIVITY_NEW_TASK|FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
//此时需要重置task 重置完后 taskTop为ActivityB的ActivityRecord
if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
taskTop = resetTaskIfNeededLocked(taskTop, r);
}
//startFlags为0
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
//... 这些代码都不会被执行
}
//根据launchFlags和被启动的activity的信息 设置resueTask addingTask变量的值
//没设置 Intent.FLAG_ACTIVITY_CLEAR_TASK
if ((launchFlags &
(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
== (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
//... 这些代码都不会被执行
} else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//... 这些代码都不会被执行
} else if (r.realActivity.equals(taskTop.task.realActivity)) {
//... 这些代码都不会被执行
} else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
//因为从Launcher程序启动时launchFlags设置了FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
//所以不会进入该分支
//... 这些代码都不会被执行
} else if (!taskTop.task.rootWasReset) {
//... 这些代码都不会被执行
}
//此时addingToTask为false,reuseTask为null,故此显示栈顶Actvity即可
if (!addingToTask && reuseTask == null) {
// We didn't do anything... but it was needed (a.k.a., client
// don't use that intent!) And for paranoia, make
// sure we have correctly resumed the top activity.
if (doResume) {
resumeTopActivityLocked(null, options);
} else {
ActivityOptions.abort(options);
}
return ActivityManager.START_TASK_TO_FRONT;
}
}
}
}
//... 以下代码都不会被执行
}
实际场景2:
应用内有两个Activity,A和B,A为第应用入口Activity,从A可跳转至B,A的启动模式都为standard,B的启动模式为singleTop
此时已从Launchenr程序打开应用,启动了Actvity A,再从A跳转至B,此时的任务调度情况:
此时不会创建新的Task,而是将B的ActivityRecord加入到A所在的task里
任务调度执行如下所示:
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, int startFlags, boolean doResume,
Bundle options) {
//...
//此时launcheFlags为0
int launchFlags = intent.getFlags();
//notTop为null
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
//默认情况下startFlags不会设置START_FLAG_ONLY_IF_NEEDED
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
//...这里的代码不会执行
}
//r.launchMode = ActivityInfo.LAUNCH_SINGLE_TASK
if (sourceRecord == null) {
//这里的代码不会执行
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//这里的代码不会执行
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
}
//此时r.resultTo!=null launchFlags设置了Intent.FLAG_ACTIVITY_NEW_TASK
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//...
r.resultTo = null;
}
//addingToTask如果为true表示正在添加至某个task,后续需要将r添加至sourceRecord所在的task
boolean addingToTask = false;
//movedHome表示是否移动home task
boolean movedHome = false;
TaskRecord reuseTask = null;
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
//此时 r.resultTo = null
if (r.resultTo == null) {
//此时找到的taskTop是Activity A的ActivityRecord,
//因为Actvity B和A的ActivityRecord所在的Task是相关的
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
//找到了相关task
if (taskTop != null) {
//重设task的intent
if (taskTop.task.intent == null) {
//...
}
//此时找到的task已在栈顶
ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
if (curTop != null && curTop.task != taskTop.task) {
//... 这里的代码不会执行
}
//launchFlags为0
if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
taskTop = resetTaskIfNeededLocked(taskTop, r);
}
//... 一般情况下startFlags 不会设置 START_FLAG_ONLY_IF_NEEDED
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
//...
}
// ==================== begin
// launchFlags此时为0
if ((launchFlags &
(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
== (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
//...这里的代码不执行
} else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
// 故此会进入该分支
//因为B还从未启动,故此得到的top为null
ActivityRecord top = performClearTaskLocked(
taskTop.task.taskId, r, launchFlags);
if (top != null) {
//...这里的代码不执行
} else {
addingToTask = true;
sourceRecord = taskTop;
}
} else if (r.realActivity.equals(taskTop.task.realActivity)) {
//...这里的代码不执行
} else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
//...这里的代码不执行
} else if (!taskTop.task.rootWasReset) {
//...这里的代码不执行
}
// ==================== end
// 此时 addingToTask为true
if (!addingToTask && reuseTask == null) {
//...这里的代码不执行
}
}
}
}
//...
if (r.packageName != null) {
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
//此时task还没有B的ActivityRecord,故此不会进入下述分支
if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
//...这里的代码不执行
}
}
} else {
//...这里的代码不执行
}
boolean newTask = false;
boolean keepCurTransition = false;
// 此时 r.resultTo == null addingToTask为true sourceRecord != null
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
//...这里的代码不执行
} else if (sourceRecord != null) {
if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
//...这里的代码不执行
} else if (!addingToTask &&
(launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
//...这里的代码不执行
}
//将B的ActivityRecord加入A的ActivityRecord所在的Task里
r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
//...
} else {
//...这里的代码不执行
}
//...
startActivityLocked(r, newTask, doResume, keepCurTransition, options);
return ActivityManager.START_SUCCESS;
}
从上面的分析可以看出来,Activity和Task的调度算法非常复杂,需结合实际场景才好分析,只有这样才知道是否需要新建Task,还是将新的ActivityRecord加入到已有的Task里,不过我们如果能理解启动模式的一些特点,对理解调度算法会有很大帮助。
大家可以结合下述场景分析调度算法:
1.从通知栏启动Activity:
假设应用有Activity A ,Activity A已启动,
此时发了一个通知,该通知用于启动Activity A,启动Activity A时不加任何特殊flag
点击通知,针对以下情况对任务调度情况进行分析:
1) Activity A的启动模式为standard
2) Activity A的启动模式为singleTop
3) Activity A的启动模式为singleTask
4) Activity A的启动模式为singleInstance
2.跨应用跳转Activity
假设应用app1有一个Activity A,另一个应用app2有一个Activity B
Activity A可跳转至Activity B
因为Activity A和Actiivty B在不同应用,所以Activity的taskffinity必然不同
现在Activity A已启动,跳转至Activity B,
针对以下4种情况分析跳转之后的Activity Task情况
1) Activity B的启动模式为standard
2) Activity B的启动模式为singleTop
3) Activity B的启动模式为singleTask
4) Activity B的启动模式为singleInstance
如果大家对上述场景分析有兴趣的话,可以在评论里一起探讨结果。
转载自http://ju.outofmemory.cn/entry/169879