Android应用程序启动过程源代码分析
前文简要介绍了Android应用程序的Activity的启动过程。在Android系统中,应用程序是由Activity组成的,因此,应用程序的启动过程实际上就是应用程序中的默认Activity的启动过程,本文将详细分析应用程序框架层的源代码,了解Android应用程序的启动过程。
在上一篇文章Android应用程序的Activity启动过程简要介绍和学习计划中,我们举例子说明了启动Android应用程序中的Activity的两种情景,其中,在手机屏幕中点击应用程序图标的情景就会引发Android应用程序中的默认Activity的启动,从而把应用程序启动起来。这种启动方式的特点是会启动一个新的进程来加载相应的Activity。这里,我们继续以这个例子为例来说明Android应用程序的启动过程,即MainActivity的启动过程。
MainActivity的启动过程如下图所示:
点击查看大图
下面详细分析每一步是如何实现的。
Step 1. Launcher.startActivitySafely
在Android系统中,应用程序是由Launcher启动起来的,其实,Launcher本身也是一个应用程序,其它的应用程序安装后,就会Launcher的界面上出现一个相应的图标,点击这个图标时,Launcher就会对应的应用程序启动起来。
Launcher的源代码工程在packages/apps/Launcher2目录下,负责启动其它应用程序的源代码实现在src/com/android/launcher2/Launcher.java文件中:
[java] view plain copy
- /**
- *Defaultlauncherapplication.
- */
- publicfinalclassLauncherextendsActivity
- implementsView.OnClickListener,OnLongClickListener,LauncherModel.Callbacks,AllAppsView.Watcher{
- ......
- /**
- *Launchestheintentreferredbytheclickedshortcut.
- *
- *@paramvTheviewrepresentingtheclickedshortcut.
- */
- publicvoidonClick(Viewv){
- Objecttag=v.getTag();
- if(taginstanceofShortcutInfo){
- //Openshortcut
- finalIntentintent=((ShortcutInfo)tag).intent;
- int[]pos=newint[2];
- v.getLocationOnScreen(pos);
- intent.setSourceBounds(newRect(pos[0],pos[1],
- pos[0]+v.getWidth(),pos[1]+v.getHeight()));
- startActivitySafely(intent,tag);
- }elseif(taginstanceofFolderInfo){
- ......
- }elseif(v==mHandleView){
- ......
- }
- }
- voidstartActivitySafely(Intentintent,Objecttag){
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- try{
- startActivity(intent);
- }catch(ActivityNotFoundExceptione){
- ......
- }catch(SecurityExceptione){
- ......
- }
- }
- ......
- }
[html] view plain copy
- <activityandroid:name=".MainActivity"
- android:label="@string/app_name">
- <intent-filter>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
Step 2. Activity.startActivity
在Step 1中,我们看到,Launcher继承于Activity类,而Activity类实现了startActivity函数,因此,这里就调用了Activity.startActivity函数,它实现在frameworks/base/core/java/android/app/Activity.java文件中:
[java] view plain copy
- publicclassActivityextendsContextThemeWrapper
- implementsLayoutInflater.Factory,
- Window.Callback,KeyEvent.Callback,
- OnCreateContextMenuListener,ComponentCallbacks{
- ......
- @Override
- publicvoidstartActivity(Intentintent){
- startActivityForResult(intent,-1);
- }
- ......
- }
Step 3.Activity.startActivityForResult
这个函数也是实现在frameworks/base/core/java/android/app/Activity.java文件中:
- publicclassActivityextendsContextThemeWrapper
- implementsLayoutInflater.Factory,
- Window.Callback,KeyEvent.Callback,
- OnCreateContextMenuListener,ComponentCallbacks{
- ......
- publicvoidstartActivityForResult(Intentintent,intrequestCode){
- if(mParent==null){
- Instrumentation.ActivityResultar=
- mInstrumentation.execStartActivity(
- this,mMainThread.getApplicationThread(),mToken,this,
- intent,requestCode);
- ......
- }else{
- ......
- }
- ......
- }
这里的mMainThread也是Activity类的成员变量,它的类型是ActivityThread,它代表的是应用程序的主线程,我们在Android系统在新进程中启动自定义服务过程(startService)的原理分析一文中已经介绍过了。这里通过mMainThread.getApplicationThread获得它里面的ApplicationThread成员变量,它是一个Binder对象,后面我们会看到,ActivityManagerService会使用它来和ActivityThread来进行进程间通信。这里我们需注意的是,这里的mMainThread代表的是Launcher应用程序运行的进程。
这里的mToken也是Activity类的成员变量,它是一个Binder对象的远程接口。
Step 4. Instrumentation.execStartActivity
这个函数定义在frameworks/base/core/java/android/app/Instrumentation.java文件中:
[java] view plain copy
- publicclassInstrumentation{
- ......
- publicActivityResultexecStartActivity(
- Contextwho,IBindercontextThread,IBindertoken,Activitytarget,
- Intentintent,intrequestCode){
- IApplicationThreadwhoThread=(IApplicationThread)contextThread;
- if(mActivityMonitors!=null){
- ......
- }
- try{
- intresult=ActivityManagerNative.getDefault()
- .startActivity(whoThread,intent,
- intent.resolveTypeIfNeeded(who.getContentResolver()),
- null,0,token,target!=null?target.mEmbeddedID:null,
- requestCode,false,false);
- ......
- }catch(RemoteExceptione){
- }
- returnnull;
- }
- ......
- }
这里的intent.resolveTypeIfNeeded返回这个intent的MIME类型,在这个例子中,没有AndroidManifest.xml设置MainActivity的MIME类型,因此,这里返回null。
这里的target不为null,但是target.mEmbddedID为null,我们不用关注。
Step 5. ActivityManagerProxy.startActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
[java] view plain copy
- classActivityManagerProxyimplementsIActivityManager
- {
- ......
- publicintstartActivity(IApplicationThreadcaller,Intentintent,
- StringresolvedType,Uri[]grantedUriPermissions,intgrantedMode,
- IBinderresultTo,StringresultWho,
- intrequestCode,booleanonlyIfNeeded,
- booleandebug)throwsRemoteException{
- Parceldata=Parcel.obtain();
- Parcelreply=Parcel.obtain();
- data.writeInterfaceToken(IActivityManager.descriptor);
- data.writeStrongBinder(caller!=null?caller.asBinder():null);
- intent.writeToParcel(data,0);
- data.writeString(resolvedType);
- data.writeTypedArray(grantedUriPermissions,0);
- data.writeInt(grantedMode);
- data.writeStrongBinder(resultTo);
- data.writeString(resultWho);
- data.writeInt(requestCode);
- data.writeInt(onlyIfNeeded?1:0);
- data.writeInt(debug?1:0);
- mRemote.transact(START_ACTIVITY_TRANSACTION,data,reply,0);
- reply.readException();
- intresult=reply.readInt();
- reply.recycle();
- data.recycle();
- returnresult;
- }
- ......
- }
Step 6. ActivityManagerService.startActivity
上一步Step 5通过Binder驱动程序就进入到ActivityManagerService的startActivity函数来了,它定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
[java] view plain copy
- publicfinalclassActivityManagerServiceextendsActivityManagerNative
- implementsWatchdog.Monitor,BatteryStatsImpl.BatteryCallback{
- ......
- publicfinalintstartActivity(IApplicationThreadcaller,
- Intentintent,StringresolvedType,Uri[]grantedUriPermissions,
- intgrantedMode,IBinderresultTo,
- StringresultWho,intrequestCode,booleanonlyIfNeeded,
- booleandebug){
- returnmMainStack.startActivityMayWait(caller,intent,resolvedType,
- grantedUriPermissions,grantedMode,resultTo,resultWho,
- requestCode,onlyIfNeeded,debug,null,null);
- }
- ......
- }
Step 7.ActivityStack.startActivityMayWait
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- finalintstartActivityMayWait(IApplicationThreadcaller,
- Intentintent,StringresolvedType,Uri[]grantedUriPermissions,
- intgrantedMode,IBinderresultTo,
- StringresultWho,intrequestCode,booleanonlyIfNeeded,
- booleandebug,WaitResultoutResult,Configurationconfig){
- ......
- booleancomponentSpecified=intent.getComponent()!=null;
- //Don'tmodifytheclient'sobject!
- intent=newIntent(intent);
- //CollectinformationaboutthetargetoftheIntent.
- ActivityInfoaInfo;
- try{
- ResolveInforInfo=
- AppGlobals.getPackageManager().resolveIntent(
- intent,resolvedType,
- PackageManager.MATCH_DEFAULT_ONLY
- |ActivityManagerService.STOCK_PM_FLAGS);
- aInfo=rInfo!=null?rInfo.activityInfo:null;
- }catch(RemoteExceptione){
- ......
- }
- if(aInfo!=null){
- //Storethefoundtargetbackintotheintent,becausenowthat
- //wehaveitweneverwanttodothisagain.Forexample,ifthe
- //usernavigatesbacktothispointinthehistory,weshould
- //alwaysrestarttheexactsameactivity.
- intent.setComponent(newComponentName(
- aInfo.applicationInfo.packageName,aInfo.name));
- ......
- }
- synchronized(mService){
- intcallingPid;
- intcallingUid;
- if(caller==null){
- ......
- }else{
- callingPid=callingUid=-1;
- }
- mConfigWillChange=config!=null
- &&mService.mConfiguration.diff(config)!=0;
- ......
- if(mMainStack&&aInfo!=null&&
- (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE)!=0){
- ......
- }
- intres=startActivityLocked(caller,intent,resolvedType,
- grantedUriPermissions,grantedMode,aInfo,
- resultTo,resultWho,requestCode,callingPid,callingUid,
- onlyIfNeeded,componentSpecified);
- if(mConfigWillChange&&mMainStack){
- ......
- }
- ......
- if(outResult!=null){
- ......
- }
- returnres;
- }
- }
- ......
- }
下面语句对参数intent的内容进行解析,得到MainActivity的相关信息,保存在aInfo变量中:
[java] view plain copy
- ActivityInfoaInfo;
- try{
- ResolveInforInfo=
- AppGlobals.getPackageManager().resolveIntent(
- intent,resolvedType,
- PackageManager.MATCH_DEFAULT_ONLY
- |ActivityManagerService.STOCK_PM_FLAGS);
- aInfo=rInfo!=null?rInfo.activityInfo:null;
- }catch(RemoteExceptione){
- ......
- }
此外,函数开始的地方调用intent.getComponent()函数的返回值不为null,因此,这里的componentSpecified变量为true。
接下去就调用startActivityLocked进一步处理了。
Step 8. ActivityStack.startActivityLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- finalintstartActivityLocked(IApplicationThreadcaller,
- Intentintent,StringresolvedType,
- Uri[]grantedUriPermissions,
- intgrantedMode,ActivityInfoaInfo,IBinderresultTo,
- StringresultWho,intrequestCode,
- intcallingPid,intcallingUid,booleanonlyIfNeeded,
- booleancomponentSpecified){
- interr=START_SUCCESS;
- ProcessRecordcallerApp=null;
- if(caller!=null){
- callerApp=mService.getRecordForAppLocked(caller);
- if(callerApp!=null){
- callingPid=callerApp.pid;
- callingUid=callerApp.info.uid;
- }else{
- ......
- }
- }
- ......
- ActivityRecordsourceRecord=null;
- ActivityRecordresultRecord=null;
- if(resultTo!=null){
- intindex=indexOfTokenLocked(resultTo);
- ......
- if(index>=0){
- sourceRecord=(ActivityRecord)mHistory.get(index);
- if(requestCode>=0&&!sourceRecord.finishing){
- ......
- }
- }
- }
- intlaunchFlags=intent.getFlags();
- if((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT)!=0
- &&sourceRecord!=null){
- ......
- }
- if(err==START_SUCCESS&&intent.getComponent()==null){
- ......
- }
- if(err==START_SUCCESS&&aInfo==null){
- ......
- }
- if(err!=START_SUCCESS){
- ......
- }
- ......
- ActivityRecordr=newActivityRecord(mService,this,callerApp,callingUid,
- intent,resolvedType,aInfo,mService.mConfiguration,
- resultRecord,resultWho,requestCode,componentSpecified);
- ......
- returnstartActivityUncheckedLocked(r,sourceRecord,
- grantedUriPermissions,grantedMode,onlyIfNeeded,true);
- }
- ......
- }
前面说过,参数resultTo是Launcher这个Activity里面的一个Binder对象,通过它可以获得Launcher这个Activity的相关信息,保存在sourceRecord变量中。
再接下来,创建即将要启动的Activity的相关信息,并保存在r变量中:
[java] view plain copy
- ActivityRecordr=newActivityRecord(mService,this,callerApp,callingUid,
- intent,resolvedType,aInfo,mService.mConfiguration,
- resultRecord,resultWho,requestCode,componentSpecified);
Step 9. ActivityStack.startActivityUncheckedLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- finalintstartActivityUncheckedLocked(ActivityRecordr,
- ActivityRecordsourceRecord,Uri[]grantedUriPermissions,
- intgrantedMode,booleanonlyIfNeeded,booleandoResume){
- finalIntentintent=r.intent;
- finalintcallingUid=r.launchedFromUid;
- intlaunchFlags=intent.getFlags();
- //We'llinvokeonUserLeavingbeforeonPauseonlyifthelaunching
- //activitydidnotexplicitlystatethatthisisanautomatedlaunch.
- mUserLeaving=(launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION)==0;
- ......
- ActivityRecordnotTop=(launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
- !=0?r:null;
- //IftheonlyIfNeededflagisset,thenwecandothisiftheactivity
- //beinglaunchedisthesameastheonemakingthecall...or,as
- //aspecialcase,ifwedonotknowthecallerthenwecountthe
- //currenttopactivityasthecaller.
- if(onlyIfNeeded){
- ......
- }
- if(sourceRecord==null){
- ......
- }elseif(sourceRecord.launchMode==ActivityInfo.LAUNCH_SINGLE_INSTANCE){
- ......
- }elseif(r.launchMode==ActivityInfo.LAUNCH_SINGLE_INSTANCE
- ||r.launchMode==ActivityInfo.LAUNCH_SINGLE_TASK){
- ......
- }
- if(r.resultTo!=null&&(launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK)!=0){
- ......
- }
- booleanaddingToTask=false;
- 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){
- //Ifbringtofrontisrequested,andnoresultisrequested,and
- //wecanfindataskthatwasstartedwiththissame
- //component,theninsteadoflaunchingbringthatonetothefront.
- if(r.resultTo==null){
- //Seeifthereisatasktobringtothefront.Ifthisis
- //aSINGLE_INSTANCEactivity,therecanbeoneandonlyone
- //instanceofitinthehistory,anditisalwaysinitsown
- //uniquetask,sowedoaspecialsearch.
- ActivityRecordtaskTop=r.launchMode!=ActivityInfo.LAUNCH_SINGLE_INSTANCE
- ?findTaskLocked(intent,r.info)
- :findActivityLocked(intent,r.info);
- if(taskTop!=null){
- ......
- }
- }
- }
- ......
- if(r.packageName!=null){
- //Iftheactivitybeinglaunchedisthesameastheonecurrently
- //atthetop,thenweneedtocheckifitshouldonlybelaunched
- //once.
- ActivityRecordtop=topRunningNonDelayedActivityLocked(notTop);
- if(top!=null&&r.resultTo==null){
- if(top.realActivity.equals(r.realActivity)){
- ......
- }
- }
- }else{
- ......
- }
- booleannewTask=false;
- //Shouldthisbeconsideredanewtask?
- if(r.resultTo==null&&!addingToTask
- &&(launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK)!=0){
- //todo:shoulddobettermanagementofintegers.
- mService.mCurTask++;
- if(mService.mCurTask<=0){
- mService.mCurTask=1;
- }
- r.task=newTaskRecord(mService.mCurTask,r.info,intent,
- (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH)!=0);
- ......
- newTask=true;
- if(mMainStack){
- mService.addRecentTaskLocked(r.task);
- }
- }elseif(sourceRecord!=null){
- ......
- }else{
- ......
- }
- ......
- startActivityLocked(r,newTask,doResume);
- returnSTART_SUCCESS;
- }
- ......
- }
这个intent的标志值的位Intent.FLAG_ACTIVITY_NO_USER_ACTION没有置位,因此 ,成员变量mUserLeaving的值为true。
这个intent的标志值的位Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP也没有置位,因此,变量notTop的值为null。
由于在这个例子的AndroidManifest.xml文件中,MainActivity没有配置launchMode属值,因此,这里的r.launchMode为默认值0,表示以标准(Standard,或者称为ActivityInfo.LAUNCH_MULTIPLE)的方式来启动这个Activity。Activity的启动方式有四种,其余三种分别是ActivityInfo.LAUNCH_SINGLE_INSTANCE、ActivityInfo.LAUNCH_SINGLE_TASK和ActivityInfo.LAUNCH_SINGLE_TOP,具体可以参考官方网站http://developer.android.com/reference/android/content/pm/ActivityInfo.html。
传进来的参数r.resultTo为null,表示Launcher不需要等这个即将要启动的MainActivity的执行结果。
由于这个intent的标志值的位Intent.FLAG_ACTIVITY_NEW_TASK被置位,而且Intent.FLAG_ACTIVITY_MULTIPLE_TASK没有置位,因此,下面的if语句会被执行:
[java] view plain copy
- 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){
- //Ifbringtofrontisrequested,andnoresultisrequested,and
- //wecanfindataskthatwasstartedwiththissame
- //component,theninsteadoflaunchingbringthatonetothefront.
- if(r.resultTo==null){
- //Seeifthereisatasktobringtothefront.Ifthisis
- //aSINGLE_INSTANCEactivity,therecanbeoneandonlyone
- //instanceofitinthehistory,anditisalwaysinitsown
- //uniquetask,sowedoaspecialsearch.
- ActivityRecordtaskTop=r.launchMode!=ActivityInfo.LAUNCH_SINGLE_INSTANCE
- ?findTaskLocked(intent,r.info)
- :findActivityLocked(intent,r.info);
- if(taskTop!=null){
- ......
- }
- }
- }
接着往下看:
[java] view plain copy
- if(r.packageName!=null){
- //Iftheactivitybeinglaunchedisthesameastheonecurrently
- //atthetop,thenweneedtocheckifitshouldonlybelaunched
- //once.
- ActivityRecordtop=topRunningNonDelayedActivityLocked(notTop);
- if(top!=null&&r.resultTo==null){
- if(top.realActivity.equals(r.realActivity)){
- ......
- }
- }
- }
执行到这里,我们知道,要在一个新的Task里面来启动这个Activity了,于是新创建一个Task:
[java] view plain copy
- if(r.resultTo==null&&!addingToTask
- &&(launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK)!=0){
- //todo:shoulddobettermanagementofintegers.
- mService.mCurTask++;
- if(mService.mCurTask<=0){
- mService.mCurTask=1;
- }
- r.task=newTaskRecord(mService.mCurTask,r.info,intent,
- (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH)!=0);
- ......
- newTask=true;
- if(mMainStack){
- mService.addRecentTaskLocked(r.task);
- }
- }
最后就进入startActivityLocked(r, newTask, doResume)进一步处理了。这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- privatefinalvoidstartActivityLocked(ActivityRecordr,booleannewTask,
- booleandoResume){
- finalintNH=mHistory.size();
- intaddPos=-1;
- if(!newTask){
- ......
- }
- //Placeanewactivityattopofstack,soitisnexttointeract
- //withtheuser.
- if(addPos<0){
- addPos=NH;
- }
- //Ifwearenotplacingthenewactivityfrontmost,wedonotwant
- //todelivertheonUserLeavingcallbacktotheactualfrontmost
- //activity
- if(addPos<NH){
- ......
- }
- //Slottheactivityintothehistorystackandproceed
- mHistory.add(addPos,r);
- r.inHistory=true;
- r.frontOfTask=newTask;
- r.task.numActivities++;
- if(NH>0){
- //Wewanttoshowthestartingpreviewwindowifweare
- //switchingtoanewtask,orthenextactivity'sprocessis
- //notcurrentlyrunning.
- ......
- }else{
- //Ifthisisthefirstactivity,don'tdoanyfancyanimations,
- //becausethereisnothingforittoanimateontopof.
- ......
- }
- ......
- if(doResume){
- resumeTopActivityLocked(null);
- }
- }
- ......
- }
这里传进来的参数doResume为true,于是调用resumeTopActivityLocked进一步操作。
Step 10. Activity.resumeTopActivityLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
- publicclassActivityStack{
- ......
- /**
- *Ensurethatthetopactivityinthestackisresumed.
- *
- *@paramprevThepreviouslyresumedactivity,forwhenintheprocess
- *ofpausing;canbenulltocallfromelsewhere.
- *
- *@returnReturnstrueifsomethingisbeingresumed,orfalseif
- *nothinghappened.
- */
- finalbooleanresumeTopActivityLocked(ActivityRecordprev){
- //Findthefirstactivitythatisnotfinishing.
- ActivityRecordnext=topRunningActivityLocked(null);
- //Rememberhowwe'llprocessthispause/resumesituation,andensure
- //thatthestateisresethoweverwewindupproceeding.
- finalbooleanuserLeaving=mUserLeaving;
- mUserLeaving=false;
- if(next==null){
- ......
- }
- next.delayedResume=false;
- //Ifthetopactivityistheresumedone,nothingtodo.
- if(mResumedActivity==next&&next.state==ActivityState.RESUMED){
- ......
- }
- //Ifwearesleeping,andthereisnoresumedactivity,andthetop
- //activityispaused,wellthatisthestatewewant.
- if((mService.mSleeping||mService.mShuttingDown)
- &&mLastPausedActivity==next&&next.state==ActivityState.PAUSED){
- ......
- }
- ......
- //Ifwearecurrentlypausinganactivity,thendon'tdoanything
- //untilthatisdone.
- if(mPausingActivity!=null){
- ......
- }
- ......
- //Weneedtostartpausingthecurrentactivitysothetopone
- //canberesumed...
- if(mResumedActivity!=null){
- ......
- startPausingLocked(userLeaving,false);
- returntrue;
- }
- ......
- }
- ......
- }
接下来把mUserLeaving的保存在本地变量userLeaving中,然后重新设置为false,在上面的Step 9中,mUserLeaving的值为true,因此,这里的userLeaving为true。
这里的mResumedActivity为Launcher,因为Launcher是当前正被执行的Activity。
当我们处理休眠状态时,mLastPausedActivity保存堆栈顶端的Activity,因为当前不是休眠状态,所以mLastPausedActivity为null。
有了这些信息之后,下面的语句就容易理解了:
[java] view plain copy
- //Ifthetopactivityistheresumedone,nothingtodo.
- if(mResumedActivity==next&&next.state==ActivityState.RESUMED){
- ......
- }
- //Ifwearesleeping,andthereisnoresumedactivity,andthetop
- //activityispaused,wellthatisthestatewewant.
- if((mService.mSleeping||mService.mShuttingDown)
- &&mLastPausedActivity==next&&next.state==ActivityState.PAUSED){
- ......
- }
上面两个条件都不满足,因此,在继续往下执行之前,首先要把当处于Resumed状态的Activity推入Paused状态,然后才可以启动新的Activity。但是在将当前这个Resumed状态的Activity推入Paused状态之前,首先要看一下当前是否有Activity正在进入Pausing状态,如果有的话,当前这个Resumed状态的Activity就要稍后才能进入Paused状态了,这样就保证了所有需要进入Paused状态的Activity串行处理。
这里没有处于Pausing状态的Activity,即mPausingActivity为null,而且mResumedActivity也不为null,于是就调用startPausingLocked函数把Launcher推入Paused状态去了。
Step 11. ActivityStack.startPausingLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- privatefinalvoidstartPausingLocked(booleanuserLeaving,booleanuiSleeping){
- if(mPausingActivity!=null){
- ......
- }
- ActivityRecordprev=mResumedActivity;
- if(prev==null){
- ......
- }
- ......
- mResumedActivity=null;
- mPausingActivity=prev;
- mLastPausedActivity=prev;
- prev.state=ActivityState.PAUSING;
- ......
- if(prev.app!=null&&prev.app.thread!=null){
- ......
- try{
- ......
- prev.app.thread.schedulePauseActivity(prev,prev.finishing,userLeaving,
- prev.configChangeFlags);
- ......
- }catch(Exceptione){
- ......
- }
- }else{
- ......
- }
- ......
- }
- ......
- }
函数首先把mResumedActivity保存在本地变量prev中。在上一步Step 10中,说到mResumedActivity就是Launcher,因此,这里把Launcher进程中的ApplicationThread对象取出来,通过它来通知Launcher这个Activity它要进入Paused状态了。当然,这里的prev.app.thread是一个ApplicationThread对象的远程接口,通过调用这个远程接口的schedulePauseActivity来通知Launcher进入Paused状态。
参数prev.finishing表示prev所代表的Activity是否正在等待结束的Activity列表中,由于Laucher这个Activity还没结束,所以这里为false;参数prev.configChangeFlags表示哪些config发生了变化,这里我们不关心它的值。
Step 12.ApplicationThreadProxy.schedulePauseActivity
这个函数定义在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中:
[java] view plain copy
- classApplicationThreadProxyimplementsIApplicationThread{
- ......
- publicfinalvoidschedulePauseActivity(IBindertoken,booleanfinished,
- booleanuserLeaving,intconfigChanges)throwsRemoteException{
- Parceldata=Parcel.obtain();
- data.writeInterfaceToken(IApplicationThread.descriptor);
- data.writeStrongBinder(token);
- data.writeInt(finished?1:0);
- data.writeInt(userLeaving?1:0);
- data.writeInt(configChanges);
- mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION,data,null,
- IBinder.FLAG_ONEWAY);
- data.recycle();
- }
- ......
- }
这个函数通过Binder进程间通信机制进入到ApplicationThread.schedulePauseActivity函数中。
Step 13. ApplicationThread.schedulePauseActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中,它是ActivityThread的内部类:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalclassApplicationThreadextendsApplicationThreadNative{
- ......
- publicfinalvoidschedulePauseActivity(IBindertoken,booleanfinished,
- booleanuserLeaving,intconfigChanges){
- queueOrSendMessage(
- finished?H.PAUSE_ACTIVITY_FINISHING:H.PAUSE_ACTIVITY,
- token,
- (userLeaving?1:0),
- configChanges);
- }
- ......
- }
- ......
- }
上面说到,这里的finished值为false,因此,queueOrSendMessage的第一个参数值为H.PAUSE_ACTIVITY,表示要暂停token所代表的Activity,即Launcher。
Step 14. ActivityThread.queueOrSendMessage
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
- publicfinalclassActivityThread{
- ......
- privatefinalvoidqueueOrSendMessage(intwhat,Objectobj,intarg1){
- queueOrSendMessage(what,obj,arg1,0);
- }
- privatefinalvoidqueueOrSendMessage(intwhat,Objectobj,intarg1,intarg2){
- synchronized(this){
- ......
- Messagemsg=Message.obtain();
- msg.what=what;
- msg.obj=obj;
- msg.arg1=arg1;
- msg.arg2=arg2;
- mH.sendMessage(msg);
- }
- }
- ......
- }
Step 15. H.handleMessage
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalclassHextendsHandler{
- ......
- publicvoidhandleMessage(Messagemsg){
- ......
- switch(msg.what){
- ......
- casePAUSE_ACTIVITY:
- handlePauseActivity((IBinder)msg.obj,false,msg.arg1!=0,msg.arg2);
- maybeSnapshot();
- break;
- ......
- }
- ......
- }
- ......
- }
这里调用ActivityThread.handlePauseActivity进一步操作,msg.obj是一个ActivityRecord对象的引用,它代表的是Launcher这个Activity。
Step 16.ActivityThread.handlePauseActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalvoidhandlePauseActivity(IBindertoken,booleanfinished,
- booleanuserLeaving,intconfigChanges){
- ActivityClientRecordr=mActivities.get(token);
- if(r!=null){
- //Slog.v(TAG,"userLeaving="+userLeaving+"handlingpauseof"+r);
- if(userLeaving){
- performUserLeavingActivity(r);
- }
- r.activity.mConfigChangeFlags|=configChanges;
- Bundlestate=performPauseActivity(token,finished,true);
- //Makesureanypendingwritesarenowcommitted.
- QueuedWork.waitToFinish();
- //Telltheactivitymanagerwehavepaused.
- try{
- ActivityManagerNative.getDefault().activityPaused(token,state);
- }catch(RemoteExceptionex){
- }
- }
- }
- ......
- }
Step 17. ActivityManagerProxy.activityPaused
这个函数定义在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
- classActivityManagerProxyimplementsIActivityManager
- {
- ......
- publicvoidactivityPaused(IBindertoken,Bundlestate)throwsRemoteException
- {
- Parceldata=Parcel.obtain();
- Parcelreply=Parcel.obtain();
- data.writeInterfaceToken(IActivityManager.descriptor);
- data.writeStrongBinder(token);
- data.writeBundle(state);
- mRemote.transact(ACTIVITY_PAUSED_TRANSACTION,data,reply,0);
- reply.readException();
- data.recycle();
- reply.recycle();
- }
- ......
- }
Step 18.ActivityManagerService.activityPaused
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
- publicfinalclassActivityManagerServiceextendsActivityManagerNative
- implementsWatchdog.Monitor,BatteryStatsImpl.BatteryCallback{
- ......
- publicfinalvoidactivityPaused(IBindertoken,Bundleicicle){
- ......
- finallongorigId=Binder.clearCallingIdentity();
- mMainStack.activityPaused(token,icicle,false);
- ......
- }
- ......
- }
Step 19.ActivityStack.activityPaused
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- finalvoidactivityPaused(IBindertoken,Bundleicicle,booleantimeout){
- ......
- ActivityRecordr=null;
- synchronized(mService){
- intindex=indexOfTokenLocked(token);
- if(index>=0){
- r=(ActivityRecord)mHistory.get(index);
- if(!timeout){
- r.icicle=icicle;
- r.haveState=true;
- }
- mHandler.removeMessages(PAUSE_TIMEOUT_MSG,r);
- if(mPausingActivity==r){
- r.state=ActivityState.PAUSED;
- completePauseLocked();
- }else{
- ......
- }
- }
- }
- }
- ......
- }
Step 20.ActivityStack.completePauseLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
- publicclassActivityStack{
- ......
- privatefinalvoidcompletePauseLocked(){
- ActivityRecordprev=mPausingActivity;
- ......
- if(prev!=null){
- ......
- mPausingActivity=null;
- }
- if(!mService.mSleeping&&!mService.mShuttingDown){
- resumeTopActivityLocked(prev);
- }else{
- ......
- }
- ......
- }
- ......
- }
Step 21.ActivityStack.resumeTopActivityLokced
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- finalbooleanresumeTopActivityLocked(ActivityRecordprev){
- ......
- //Findthefirstactivitythatisnotfinishing.
- ActivityRecordnext=topRunningActivityLocked(null);
- //Rememberhowwe'llprocessthispause/resumesituation,andensure
- //thatthestateisresethoweverwewindupproceeding.
- finalbooleanuserLeaving=mUserLeaving;
- mUserLeaving=false;
- ......
- next.delayedResume=false;
- //Ifthetopactivityistheresumedone,nothingtodo.
- if(mResumedActivity==next&&next.state==ActivityState.RESUMED){
- ......
- returnfalse;
- }
- //Ifwearesleeping,andthereisnoresumedactivity,andthetop
- //activityispaused,wellthatisthestatewewant.
- if((mService.mSleeping||mService.mShuttingDown)
- &&mLastPausedActivity==next&&next.state==ActivityState.PAUSED){
- ......
- returnfalse;
- }
- .......
- //Weneedtostartpausingthecurrentactivitysothetopone
- //canberesumed...
- if(mResumedActivity!=null){
- ......
- returntrue;
- }
- ......
- if(next.app!=null&&next.app.thread!=null){
- ......
- }else{
- ......
- startSpecificActivityLocked(next,true,true);
- }
- returntrue;
- }
- ......
- }
Step 22. ActivityStack.startSpecificActivityLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- privatefinalvoidstartSpecificActivityLocked(ActivityRecordr,
- booleanandResume,booleancheckConfig){
- //Isthisactivity'sapplicationalreadyrunning?
- ProcessRecordapp=mService.getProcessRecordLocked(r.processName,
- r.info.applicationInfo.uid);
- ......
- if(app!=null&&app.thread!=null){
- try{
- realStartActivityLocked(r,app,andResume,checkConfig);
- return;
- }catch(RemoteExceptione){
- ......
- }
- }
- mService.startProcessLocked(r.processName,r.info.applicationInfo,true,0,
- "activity",r.intent.getComponent(),false);
- }
- ......
- }
[java] view plain copy
- ProcessRecordapp=mService.getProcessRecordLocked(r.processName,
- r.info.applicationInfo.uid);
函数最终执行ActivityManagerService.startProcessLocked函数进行下一步操作。
Step 23.ActivityManagerService.startProcessLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
[java] view plain copy
- publicfinalclassActivityManagerServiceextendsActivityManagerNative
- implementsWatchdog.Monitor,BatteryStatsImpl.BatteryCallback{
- ......
- finalProcessRecordstartProcessLocked(StringprocessName,
- ApplicationInfoinfo,booleanknownToBeDead,intintentFlags,
- StringhostingType,ComponentNamehostingName,booleanallowWhileBooting){
- ProcessRecordapp=getProcessRecordLocked(processName,info.uid);
- ......
- StringhostingNameStr=hostingName!=null
- ?hostingName.flattenToShortString():null;
- ......
- if(app==null){
- app=newProcessRecordLocked(null,info,processName);
- mProcessNames.put(processName,info.uid,app);
- }else{
- //Ifthisisanewpackageintheprocess,addthepackagetothelist
- app.addPackage(info.packageName);
- }
- ......
- startProcessLocked(app,hostingType,hostingNameStr);
- return(app.pid!=0)?app:null;
- }
- ......
- }
[java] view plain copy
- publicfinalclassActivityManagerServiceextendsActivityManagerNative
- implementsWatchdog.Monitor,BatteryStatsImpl.BatteryCallback{
- ......
- privatefinalvoidstartProcessLocked(ProcessRecordapp,
- StringhostingType,StringhostingNameStr){
- ......
- try{
- intuid=app.info.uid;
- int[]gids=null;
- try{
- gids=mContext.getPackageManager().getPackageGids(
- app.info.packageName);
- }catch(PackageManager.NameNotFoundExceptione){
- ......
- }
- ......
- intdebugFlags=0;
- ......
- intpid=Process.start("android.app.ActivityThread",
- mSimpleProcessManagement?app.processName:null,uid,uid,
- gids,debugFlags,null);
- ......
- }catch(RuntimeExceptione){
- ......
- }
- }
- ......
- }
Step 24. ActivityThread.main
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalvoidattach(booleansystem){
- ......
- mSystemThread=system;
- if(!system){
- ......
- IActivityManagermgr=ActivityManagerNative.getDefault();
- try{
- mgr.attachApplication(mAppThread);
- }catch(RemoteExceptionex){
- }
- }else{
- ......
- }
- }
- ......
- publicstaticfinalvoidmain(String[]args){
- .......
- ActivityThreadthread=newActivityThread();
- thread.attach(false);
- ......
- Looper.loop();
- .......
- thread.detach();
- ......
- }
- }
函数attach最终调用了ActivityManagerService的远程接口ActivityManagerProxy的attachApplication函数,传入的参数是mAppThread,这是一个ApplicationThread类型的Binder对象,它的作用是用来进行进程间通信的。
Step 25.ActivityManagerProxy.attachApplication
这个函数定义在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
[java] view plain copy
- classActivityManagerProxyimplementsIActivityManager
- {
- ......
- publicvoidattachApplication(IApplicationThreadapp)throwsRemoteException
- {
- Parceldata=Parcel.obtain();
- Parcelreply=Parcel.obtain();
- data.writeInterfaceToken(IActivityManager.descriptor);
- data.writeStrongBinder(app.asBinder());
- mRemote.transact(ATTACH_APPLICATION_TRANSACTION,data,reply,0);
- reply.readException();
- data.recycle();
- reply.recycle();
- }
- ......
- }
Step 26.ActivityManagerService.attachApplication
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
[java] view plain copy
- publicfinalclassActivityManagerServiceextendsActivityManagerNative
- implementsWatchdog.Monitor,BatteryStatsImpl.BatteryCallback{
- ......
- publicfinalvoidattachApplication(IApplicationThreadthread){
- synchronized(this){
- intcallingPid=Binder.getCallingPid();
- finallongorigId=Binder.clearCallingIdentity();
- attachApplicationLocked(thread,callingPid);
- Binder.restoreCallingIdentity(origId);
- }
- }
- ......
- }
Step 27.ActivityManagerService.attachApplicationLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
[java] view plain copy
- publicfinalclassActivityManagerServiceextendsActivityManagerNative
- implementsWatchdog.Monitor,BatteryStatsImpl.BatteryCallback{
- ......
- privatefinalbooleanattachApplicationLocked(IApplicationThreadthread,
- intpid){
- //Findtheapplicationrecordthatisbeingattached...eithervia
- //thepidifwearerunninginmultipleprocesses,orjustpullthe
- //nextapprecordifweareemulatingprocesswithanonymousthreads.
- ProcessRecordapp;
- if(pid!=MY_PID&&pid>=0){
- synchronized(mPidsSelfLocked){
- app=mPidsSelfLocked.get(pid);
- }
- }elseif(mStartingProcesses.size()>0){
- ......
- }else{
- ......
- }
- if(app==null){
- ......
- returnfalse;
- }
- ......
- StringprocessName=app.processName;
- try{
- thread.asBinder().linkToDeath(newAppDeathRecipient(
- app,pid,thread),0);
- }catch(RemoteExceptione){
- ......
- returnfalse;
- }
- ......
- app.thread=thread;
- app.curAdj=app.setAdj=-100;
- app.curSchedGroup=Process.THREAD_GROUP_DEFAULT;
- app.setSchedGroup=Process.THREAD_GROUP_BG_NONINTERACTIVE;
- app.forcingToForeground=null;
- app.foregroundServices=false;
- app.debugging=false;
- ......
- booleannormalMode=mProcessesReady||isAllowedWhileBooting(app.info);
- ......
- booleanbadApp=false;
- booleandidSomething=false;
- //Seeifthetopvisibleactivityiswaitingtoruninthisprocess...
- ActivityRecordhr=mMainStack.topRunningActivityLocked(null);
- if(hr!=null&&normalMode){
- if(hr.app==null&&app.info.uid==hr.info.applicationInfo.uid
- &&processName.equals(hr.processName)){
- try{
- if(mMainStack.realStartActivityLocked(hr,app,true,true)){
- didSomething=true;
- }
- }catch(Exceptione){
- ......
- }
- }else{
- ......
- }
- }
- ......
- returntrue;
- }
- ......
- }
在前面的Step 23中,已经创建了一个ProcessRecord,这里首先通过pid将它取回来,放在app变量中,然后对app的其它成员进行初始化,最后调用mMainStack.realStartActivityLocked执行真正的Activity启动操作。这里要启动的Activity通过调用mMainStack.topRunningActivityLocked(null)从堆栈顶端取回来,这时候在堆栈顶端的Activity就是MainActivity了。
Step 28. ActivityStack.realStartActivityLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
[java] view plain copy
- publicclassActivityStack{
- ......
- finalbooleanrealStartActivityLocked(ActivityRecordr,
- ProcessRecordapp,booleanandResume,booleancheckConfig)
- throwsRemoteException{
- ......
- r.app=app;
- ......
- intidx=app.activities.indexOf(r);
- if(idx<0){
- app.activities.add(r);
- }
- ......
- try{
- ......
- List<ResultInfo>results=null;
- List<Intent>newIntents=null;
- if(andResume){
- results=r.results;
- newIntents=r.newIntents;
- }
- ......
- app.thread.scheduleLaunchActivity(newIntent(r.intent),r,
- System.identityHashCode(r),
- r.info,r.icicle,results,newIntents,!andResume,
- mService.isNextTransitionForward());
- ......
- }catch(RemoteExceptione){
- ......
- }
- ......
- returntrue;
- }
- ......
- }
Step 29.ApplicationThreadProxy.scheduleLaunchActivity
这个函数定义在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中:
[java] view plain copy
- classApplicationThreadProxyimplementsIApplicationThread{
- ......
- publicfinalvoidscheduleLaunchActivity(Intentintent,IBindertoken,intident,
- ActivityInfoinfo,Bundlestate,List<ResultInfo>pendingResults,
- List<Intent>pendingNewIntents,booleannotResumed,booleanisForward)
- throwsRemoteException{
- Parceldata=Parcel.obtain();
- data.writeInterfaceToken(IApplicationThread.descriptor);
- intent.writeToParcel(data,0);
- data.writeStrongBinder(token);
- data.writeInt(ident);
- info.writeToParcel(data,0);
- data.writeBundle(state);
- data.writeTypedList(pendingResults);
- data.writeTypedList(pendingNewIntents);
- data.writeInt(notResumed?1:0);
- data.writeInt(isForward?1:0);
- mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION,data,null,
- IBinder.FLAG_ONEWAY);
- data.recycle();
- }
- ......
- }
Step 30.ApplicationThread.scheduleLaunchActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalclassApplicationThreadextendsApplicationThreadNative{
- ......
- //weusetokentoidentifythisactivitywithouthavingtosendthe
- //activityitselfbacktotheactivitymanager.(mattersmorewithipc)
- publicfinalvoidscheduleLaunchActivity(Intentintent,IBindertoken,intident,
- ActivityInfoinfo,Bundlestate,List<ResultInfo>pendingResults,
- List<Intent>pendingNewIntents,booleannotResumed,booleanisForward){
- ActivityClientRecordr=newActivityClientRecord();
- r.token=token;
- r.ident=ident;
- r.intent=intent;
- r.activityInfo=info;
- r.state=state;
- r.pendingResults=pendingResults;
- r.pendingIntents=pendingNewIntents;
- r.startsNotResumed=notResumed;
- r.isForward=isForward;
- queueOrSendMessage(H.LAUNCH_ACTIVITY,r);
- }
- ......
- }
- ......
- }
Step 31.ActivityThread.queueOrSendMessage
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalclassApplicationThreadextendsApplicationThreadNative{
- ......
- //ifthethreadhasn'tstartedyet,wedon'thavethehandler,sojust
- //savethemessagesuntilwe'reready.
- privatefinalvoidqueueOrSendMessage(intwhat,Objectobj){
- queueOrSendMessage(what,obj,0,0);
- }
- ......
- privatefinalvoidqueueOrSendMessage(intwhat,Objectobj,intarg1,intarg2){
- synchronized(this){
- ......
- Messagemsg=Message.obtain();
- msg.what=what;
- msg.obj=obj;
- msg.arg1=arg1;
- msg.arg2=arg2;
- mH.sendMessage(msg);
- }
- }
- ......
- }
- ......
- }
Step 32. H.handleMessage
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
- publicfinalclassActivityThread{
- ......
- privatefinalclassHextendsHandler{
- ......
- publicvoidhandleMessage(Messagemsg){
- ......
- switch(msg.what){
- caseLAUNCH_ACTIVITY:{
- ActivityClientRecordr=(ActivityClientRecord)msg.obj;
- r.packageInfo=getPackageInfoNoCheck(
- r.activityInfo.applicationInfo);
- handleLaunchActivity(r,null);
- }break;
- ......
- }
- ......
- }
- ......
- }
Step 33.ActivityThread.handleLaunchActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalvoidhandleLaunchActivity(ActivityClientRecordr,IntentcustomIntent){
- ......
- Activitya=performLaunchActivity(r,customIntent);
- if(a!=null){
- r.createdConfig=newConfiguration(mConfiguration);
- BundleoldState=r.state;
- handleResumeActivity(r.token,false,r.isForward);
- ......
- }else{
- ......
- }
- }
- ......
- }
Step 34.ActivityThread.performLaunchActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
[java] view plain copy
- publicfinalclassActivityThread{
- ......
- privatefinalActivityperformLaunchActivity(ActivityClientRecordr,IntentcustomIntent){
- ActivityInfoaInfo=r.activityInfo;
- if(r.packageInfo==null){
- r.packageInfo=getPackageInfo(aInfo.applicationInfo,
- Context.CONTEXT_INCLUDE_CODE);
- }
- ComponentNamecomponent=r.intent.getComponent();
- if(component==null){
- component=r.intent.resolveActivity(
- mInitialApplication.getPackageManager());
- r.intent.setComponent(component);
- }
- if(r.activityInfo.targetActivity!=null){
- component=newComponentName(r.activityInfo.packageName,
- r.activityInfo.targetActivity);
- }
- Activityactivity=null;
- try{
- java.lang.ClassLoadercl=r.packageInfo.getClassLoader();
- activity=mInstrumentation.newActivity(
- cl,component.getClassName(),r.intent);
- r.intent.setExtrasClassLoader(cl);
- if(r.state!=null){
- r.state.setClassLoader(cl);
- }
- }catch(Exceptione){
- ......
- }
- try{
- Applicationapp=r.packageInfo.makeApplication(false,mInstrumentation);
- ......
- if(activity!=null){
- ContextImplappContext=newContextImpl();
- appContext.init(r.packageInfo,r.token,this);
- appContext.setOuterContext(activity);
- CharSequencetitle=r.activityInfo.loadLabel(appContext.getPackageManager());
- Configurationconfig=newConfiguration(mConfiguration);
- ......
- activity.attach(appContext,this,getInstrumentation(),r.token,
- r.ident,app,r.intent,r.activityInfo,title,r.parent,
- r.embeddedID,r.lastNonConfigurationInstance,
- r.lastNonConfigurationChildInstances,config);
- if(customIntent!=null){
- activity.mIntent=customIntent;
- }
- r.lastNonConfigurationInstance=null;
- r.lastNonConfigurationChildInstances=null;
- activity.mStartedActivity=false;
- inttheme=r.activityInfo.getThemeResource();
- if(theme!=0){
- activity.setTheme(theme);
- }
- activity.mCalled=false;
- mInstrumentation.callActivityOnCreate(activity,r.state);
- ......
- r.activity=activity;
- r.stopped=true;
- if(!r.activity.mFinished){
- activity.performStart();
- r.stopped=false;
- }
- if(!r.activity.mFinished){
- if(r.state!=null){
- mInstrumentation.callActivityOnRestoreInstanceState(activity,r.state);
- }
- }
- if(!r.activity.mFinished){
- activity.mCalled=false;
- mInstrumentation.callActivityOnPostCreate(activity,r.state);
- if(!activity.mCalled){
- thrownewSuperNotCalledException(
- "Activity"+r.intent.getComponent().toShortString()+
- "didnotcallthroughtosuper.onPostCreate()");
- }
- }
- }
- r.paused=true;
- mActivities.put(r.token,r);
- }catch(SuperNotCalledExceptione){
- ......
- }catch(Exceptione){
- ......
- }
- returnactivity;
- }
- ......
- }
函数前面是收集要启动的Activity的相关信息,主要package和component信息:
[java] view plain copy
- ActivityInfoaInfo=r.activityInfo;
- if(r.packageInfo==null){
- r.packageInfo=getPackageInfo(aInfo.applicationInfo,
- Context.CONTEXT_INCLUDE_CODE);
- }
更多相关文章
- 箭头函数的基础使用
- Python技巧匿名函数、回调函数和高阶函数
- Android中外部程序调用方法总结
- Android之Bluetooth
- 利用BLCR加快android的启动过程
- Activity生命周期的回调,你应该知道得更多!--Android源码剖析(上)
- Android深入浅出之Zygote
- android Activity 四大启动模式探究
- Android四大基本组件介绍与生命周期