追踪Android源码演变——Activity启动全流程
主要参考的源码为Android2.3与8.0,从姜饼到奥瑞奥,Activity的主要逻辑并没有根本性的改变,更多是做了一些封装和优化,下文会在版本变化中对相关变化的代码进行对比和说明。
Launcher发送start请求1 Launcher.startActivitySafely系统启动时 PackageManagerService 解析 Androidmainfest文件, 会获取启动需要的laucher等信息,详情见《安卓源码分析与演变——PackageManager全流程》
之后根据flag走相应的启动流程
publicList<ResolveInfo>queryIntentActivities(Intentintent,
StringresolvedType,intflags){
ComponentNamecomp=intent.getComponent();
if(comp!=null){
List<ResolveInfo>list=newArrayList<ResolveInfo>(1);
ActivityInfoai=getActivityInfo(comp,flags);
if(ai!=null){
ResolveInfori=newResolveInfo();
ri.activityInfo=ai;
list.add(ri);
}
returnlist;
}
synchronized(mPackages){
StringpkgName=intent.getPackage();
if(pkgName==null){
return(List<ResolveInfo>)mActivities.queryIntent(intent,
resolvedType,flags);
}
PackageParser.Packagepkg=mPackages.get(pkgName);
if(pkg!=null){
return(List<ResolveInfo>)mActivities.queryIntentForPackage(intent,
resolvedType,flags,pkg.activities);
}
returnnull;
}
}
voidstartActivitySafely(Intentintent,Objecttag){
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try{
startActivity(intent);
}catch(ActivityNotFoundExceptione){
Toast.makeText(this,R.string.activity_not_found,Toast.LENGTH_SHORT).show();
Log.e(TAG,"Unabletolaunch.tag="+tag+"intent="+intent,e);
}catch(SecurityExceptione){
Toast.makeText(this,R.string.activity_not_found,Toast.LENGTH_SHORT).show();
Log.e(TAG,"Launcherdoesnothavethepermissiontolaunch"+intent+
".MakesuretocreateaMAINintent-filterforthecorrespondingactivity"+
"orusetheexportedattributeforthisactivity."
+"tag="+tag+"intent="+intent,e);
}
}2 Activity.startActivity
@Override
publicvoidstartActivity(Intentintent){
startActivityForResult(intent,-1);
}3 startActivityForResult
Instrument 监护系统和应用交互
ActivityThread 每个应用进程启动持有,拥有ApplicationThread变量(Binder本地对象),作为参数传递给ActivityManagerService,通知组件进入
paused状态
Activity的mToken为Ibinder(代理对象),指向ActivityManagerService的ActivityRecord
publicvoidstartActivityForResult(Intentintent,intrequestCode){
if(mParent==null){
Instrumentation.ActivityResultar=
mInstrumentation.execStartActivity(
this,mMainThread.getApplicationThread(),mToken,this,
intent,requestCode);
if(ar!=null){
mMainThread.sendActivityResult(
mToken,mEmbeddedID,requestCode,ar.getResultCode(),
ar.getResultData());
}
if(requestCode>=0){
//Ifthisstartisrequestingaresult,wecanavoidmaking
//theactivityvisibleuntiltheresultisreceived.Setting
//thiscodeduringonCreate(BundlesavedInstanceState)oronResume()willkeepthe
//activityhiddenduringthistime,toavoidflickering.
//Thiscanonlybedonewhenaresultisrequestedbecause
//thatguaranteeswewillgetinformationbackwhenthe
//activityisfinished,nomatterwhathappenstoit.
mStartedActivity=true;
}
}else{
mParent.startActivityFromChild(this,intent,requestCode);
}
}4 Instrument.execStartActivity
publicActivityResultexecStartActivity(
Contextwho,IBindercontextThread,IBindertoken,Activitytarget,
Intentintent,intrequestCode){
IApplicationThreadwhoThread=(IApplicationThread)contextThread;
if(mActivityMonitors!=null){
synchronized(mSync){
finalintN=mActivityMonitors.size();
for(inti=0;i<N;i++){
finalActivityMonitoram=mActivityMonitors.get(i);
if(am.match(who,null,intent)){
am.mHits++;
if(am.isBlocking()){
returnrequestCode>=0?am.getResult():null;
}
break;
}
}
}
}
try{
intresult=ActivityManagerNative.getDefault()
.startActivity(whoThread,intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
null,0,token,target!=null?target.mEmbeddedID:null,
requestCode,false,false);
checkStartActivityResult(result,intent);
}catch(RemoteExceptione){
}
returnnull;
}
2.3版本
ActivityManagerNative.getDefalt获取ActivityManagerService的代理对象,封装为ActivityManagerProxy
staticpublicIActivityManagergetDefault()
{
if(gDefault!=null){
//if(Config.LOGV)Log.v(
//"ActivityManager","returningcurdefault="+gDefault);
returngDefault;
}
IBinderb=ServiceManager.getService("activity");
if(Config.LOGV)Log.v(
"ActivityManager","defaultservicebinder="+b);
gDefault=asInterface(b);
if(Config.LOGV)Log.v(
"ActivityManager","defaultservice="+gDefault);
returngDefault;
}
8.0版本
intresult=ActivityManager.getService()
.startActivity(whoThread,who.getBasePackageName(),intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token,target!=null?target.mEmbeddedID:null,
requestCode,0,null,options);
取代了之前的ActivityManagerNative和proxy类,直接获取封装过的单例aidl接口IActivityManager,包括startservice等大量方法
调用asInterface()将服务端的Binder对象转换为客户端所需要的AIDL接口类型。如果客户端和服务端在同一个进程他返回的就是服务端Stub对象本身,否则返回封装的Stub.proxy对象。
privatestaticfinalSingleton<IActivityManager>IActivityManagerSingleton=
newSingleton<IActivityManager>(){
@Override
protectedIActivityManagercreate(){
finalIBinderb=ServiceManager.getService(Context.ACTIVITY_SERVICE);
finalIActivityManageram=IActivityManager.Stub.asInterface(b);
returnam;
}
};
//ServiceManager实质上是管理缓存的Ibinder对象
publicstaticIBindergetService(Stringname){
try{
IBinderservice=sCache.get(name);
if(service!=null){
returnservice;
}else{
returnBinder.allowBlocking(getIServiceManager().getService(name));
}
}catch(RemoteExceptione){
Log.e(TAG,"erroringetService",e);
}
returnnull;
}
5ActivityManagerNative.ActivityManagerProxy.startActivity
参数传递为Parcel,反序列化对象
通过ActivityManagerProxy的mRemote发送START_ACTIVITY_TRANSACTION,即进程间通信请求
(Proxy类实现IActivityManager接口,而8.0将中转的代理类去除,精简了流程)
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;
}
成员函数ActivityStack处理IPC请求,启动组件
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);
}
版本变化
8.0 使用了ActivityStarter,封装了ActivityStack、ActivityRecord、flag,intent相关的处理
@Override
publicfinalintstartActivity(IApplicationThreadcaller,StringcallingPackage,
Intentintent,StringresolvedType,IBinderresultTo,StringresultWho,intrequestCode,
intstartFlags,ProfilerInfoprofilerInfo,BundlebOptions){
returnstartActivityAsUser(caller,callingPackage,intent,resolvedType,resultTo,
resultWho,requestCode,startFlags,profilerInfo,bOptions,
UserHandle.getCallingUserId());
}
@Override
publicfinalintstartActivityAsUser(IApplicationThreadcaller,StringcallingPackage,
Intentintent,StringresolvedType,IBinderresultTo,StringresultWho,intrequestCode,
intstartFlags,ProfilerInfoprofilerInfo,BundlebOptions,intuserId){
enforceNotIsolatedCaller("startActivity");
userId=mUserController.handleIncomingUser(Binder.getCallingPid(),Binder.getCallingUid(),
userId,false,ALLOW_FULL_ONLY,"startActivity",null);
//TODO:Switchtouserappstackshere.
returnmActivityStarter.startActivityMayWait(caller,-1,callingPackage,intent,
resolvedType,null,null,resultTo,resultWho,requestCode,startFlags,
profilerInfo,null,null,bOptions,false,userId,null,null,
"startActivityAsUser");
}7ActivityStack.startActivityMayWait
解析intent信息
finalintstartActivityMayWait(IApplicationThreadcaller,
Intentintent,StringresolvedType,Uri[]grantedUriPermissions,
intgrantedMode,IBinderresultTo,
StringresultWho,intrequestCode,booleanonlyIfNeeded,
booleandebug,WaitResultoutResult,Configurationconfig){
ActivityInfoaInfo;
try{
ResolveInforInfo=
AppGlobals.getPackageManager().resolveIntent(
intent,resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
|ActivityManagerService.STOCK_PM_FLAGS);
aInfo=rInfo!=null?rInfo.activityInfo:null;
}catch(RemoteExceptione){
aInfo=null;
}
...
intres=startActivityLocked(caller,intent,resolvedType,
grantedUriPermissions,grantedMode,aInfo,
resultTo,resultWho,requestCode,callingPid,callingUid,8 ActivityStack.startActivityLocked
ActivityManagerService获取Caller对应的Proce***ecord对象,该对象指向Launcher所在进程,获取pid和uid
从mHistory寻找ActivityRecord信息,保存变量sourceActivity
9ActivityStack.startActivityUnCheckedLocked
判断标志位,是否新task,是否用户操作,根据taskAffinity属性判断新Activity的task组归属
重载方法startActivityLocked,加入栈顶,保存history
finalintstartActivityUncheckedLocked(ActivityRecordr,
ActivityRecordsourceRecord,Uri[]grantedUriPermissions,
intgrantedMode,booleanonlyIfNeeded,booleandoResume){
finalIntentintent=r.intent;
finalintcallingUid=r.launchedFromUid;
intlaunchFlags=intent.getFlags();
ActivityRecordnotTop=(launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!=0?r:null;
//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);
if(DEBUG_TASKS)Slog.v(TAG,"Startingnewactivity"+r
+"innewtask"+r.task);
newTask=true;
if(mMainStack){
mService.addRecentTaskLocked(r.task);
}
}elseif(sourceRecord!=null){
if(!addingToTask&&
(launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP)!=0){10ActivityStack.resumeTopActivityLocked
如果将要启动的Activity已经resume或者pause直接返回,否则通知进入pause状态准备启动
finalbooleanresumeTopActivityLocked(ActivityRecordprev){
//Findthefirstactivitythatisnotfinishing.
ActivityRecordnext=topRunningActivityLocked(null);
...
//Ifthetopactivityistheresumedone,nothingtodo.
if(mResumedActivity==next&&next.state==ActivityState.RESUMED){
//Makesurewehaveexecutedanypendingtransitions,sincethere
//shouldbenothinglefttodoatthispoint.
mService.mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
returnfalse;
}
//Ifwearesleeping,andthereisnoresumedactivity,andthetop
//activityispaused,wellthatisthestatewewant.
if((mService.mSleeping||mService.mShuttingDown)
&&mLastPausedActivity==next&&next.state==ActivityState.PAUSED){
//Makesurewehaveexecutedanypendingtransitions,sincethere
//shouldbenothinglefttodoatthispoint.
mService.mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
returnfalse;
}
//Theactivitymaybewaitingforstop,butthatisnolonger
//appropriateforit.
mStoppingActivities.remove(next);
mWaitingVisibleActivities.remove(next);
//Weneedtostartpausingthecurrentactivitysothetopone
//canberesumed...
if(mResumedActivity!=null){
if(DEBUG_SWITCH)Slog.v(TAG,"Skipresume:needtostartpausing");
startPausingLocked(userLeaving,false);
returntrue;
}
...
}版本变化
8.0
ActivityStackSupervisor封装了ActivityStack有关的方法
booleanresumeFocusedStackTopActivityLocked(
ActivityStacktargetStack,ActivityRecordtarget,ActivityOptionstargetOptions){
if(targetStack!=null&&isFocusedStack(targetStack)){
returntargetStack.resumeTopActivityUncheckedLocked(target,targetOptions);
}
finalActivityRecordr=mFocusedStack.topRunningActivityLocked();
if(r==null||r.state!=RESUMED){
mFocusedStack.resumeTopActivityUncheckedLocked(null,null);
}elseif(r.state==RESUMED){
//KickoffanylingeringapptransitionsformtheMoveTaskToFrontoperation.
mFocusedStack.executeAppTransition(targetOptions);
}
returnfalse;
}11 startPausingLocked
调用AMP通知主Activity,进入pause状态。延时发送handler超时消息
privatefinalvoidstartPausingLocked(booleanuserLeaving,booleanuiSleeping){
ActivityRecordprev=mResumedActivity;
...
if(prev.app!=null&&prev.app.thread!=null){
if(DEBUG_PAUSE)Slog.v(TAG,"Enqueueingpendingpause:"+prev);
try{
EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
System.identityHashCode(prev),
prev.shortComponentName);
prev.app.thread.schedulePauseActivity(prev,prev.finishing,userLeaving,
prev.configChangeFlags);
if(mMainStack){
mService.updateUsageStats(prev,false);
}
}catch(Exceptione){
//Ignoreexception,ifprocessdiedothercodewillcleanup.
Slog.w(TAG,"Exceptionthrownduringpause",e);
mPausingActivity=null;
mLastPausedActivity=null;
}
}else{
mPausingActivity=null;
mLastPausedActivity=null;
}
...
if(mPausingActivity!=null){
//Scheduleapausetimeoutincasetheappdoesn'trespond.
//Wedon'tgiveitmuchtimebecausethisdirectlyimpactsthe
//responsivenessseenbytheuser.
Messagemsg=mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
msg.obj=prev;
mHandler.sendMessageDelayed(msg,PAUSE_TIMEOUT);
if(DEBUG_PAUSE)Slog.v(TAG,"Waitingforpausetocomplete...");
}else{
//Thisactivityfailedtoschedulethe
//pause,sojusttreatitasbeingpausednow.
if(DEBUG_PAUSE)Slog.v(TAG,"Activitynotrunning,resumingnext.");
resumeTopActivityLocked(null);
}
}
casePAUSE_TIMEOUT_MSG:{
IBindertoken=(IBinder)msg.obj;
//Wedon'tatthispointknowiftheactivityisfullscreen,
//soweneedtobeconservativeandassumeitisn't.
Slog.w(TAG,"Activitypausetimeoutfor"+token);
activityPaused(token,null,true);
}12 APN.ApplicationThreadProxy.scheduePauseActivity
Ibinder发往Laucher组件(异步请求)
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();
}Launcher进入Pause状态
以上过程都在Laucher完成
13 ApplicationThread.scedulePauseActivitybinder指向ActivityRecord
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);
}14 ActivityThread.queueOrSendMessage
mH处理主线程pause操作
15ActivityThread.handleMessage16ActivityThread.handlePauseActivity通知Launcher 用户离开
通知Launcher onPause
queueWork wait数据写入(以备onResume恢复)
通知ActivityManagerService pause
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){
}
}
}版本变化
8.0
privatevoidhandlePauseActivity(IBindertoken,booleanfinished,
booleanuserLeaving,intconfigChanges,booleandontReport,intseq){
ActivityClientRecordr=mActivities.get(token);
if(DEBUG_ORDER)Slog.d(TAG,"handlePauseActivity"+r+",seq:"+seq);
if(!checkAndUpdateLifecycleSeq(seq,r,"pauseActivity")){
return;
}
if(r!=null){
//Slog.v(TAG,"userLeaving="+userLeaving+"handlingpauseof"+r);
if(userLeaving){
performUserLeavingActivity(r);
}
r.activity.mConfigChangeFlags|=configChanges;
performPauseActivity(token,finished,r.isPreHoneycomb(),"handlePauseActivity");
//Makesureanypendingwritesarenowcommitted.
if(r.isPreHoneycomb()){
QueuedWork.waitToFinish();
}
//Telltheactivitymanagerwehavepaused.
if(!dontReport){
try{
ActivityManager.getService().activityPaused(token);
}catch(RemoteExceptionex){
throwex.rethrowFromSystemServer();
}
}
mSomeActivitiesChanged=true;
}
}17 ActivityManagerProxy.activityPaused
parcel封装数据
mRemote通知ActivityManagerService(IPC)
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();
}AMS准备启动新进程
18 ActivityManagerService.activityPausedpublicfinalvoidactivityPaused(IBindertoken,Bundleicicle){
//Refusepossibleleakedfiledescriptors
if(icicle!=null&&icicle.hasFileDescriptors()){
thrownewIllegalArgumentException("FiledescriptorspassedinBundle");
}
finallongorigId=Binder.clearCallingIdentity();
mMainStack.activityPaused(token,icicle,false);
Binder.restoreCallingIdentity(origId);
}19 ActivityStack.activityPaused
移除超时
获取stack中的ActivityRecord
publicfinalvoidactivityPaused(IBindertoken,Bundleicicle){
//Refusepossibleleakedfiledescriptors
if(icicle!=null&&icicle.hasFileDescriptors()){
thrownewIllegalArgumentException("FiledescriptorspassedinBundle");
}
finallongorigId=Binder.clearCallingIdentity();
mMainStack.activityPaused(token,icicle,false);
Binder.restoreCallingIdentity(origId);
}20 ActivityStack.completePauseLocked
使pre指向mPausingActivity,并置空mPausingActivity,表示已完成pause
非睡眠和关闭状态执行resume
privatefinalvoidcompletePauseLocked(){
ActivityRecordprev=mPausingActivity;
if(DEBUG_PAUSE)Slog.v(TAG,"Completepause:"+prev);
if(prev!=null){
if(prev.finishing){
if(DEBUG_PAUSE)Slog.v(TAG,"Executingfinishofactivity:"+prev);
prev=finishCurrentActivityLocked(prev,FINISH_AFTER_VISIBLE);
}elseif(prev.app!=null){
if(DEBUG_PAUSE)Slog.v(TAG,"Enqueueingpendingstop:"+prev);
if(prev.waitingVisible){
prev.waitingVisible=false;
mWaitingVisibleActivities.remove(prev);
if(DEBUG_SWITCH||DEBUG_PAUSE)Slog.v(
TAG,"Completepause,nolongerwaiting:"+prev);
}
if(prev.configDestroy){
destroyActivityLocked(prev,true);
}else{
mStoppingActivities.add(prev);
if(mStoppingActivities.size()>3){
//Ifwealreadyhaveafewactivitieswaitingtostop,
//thengiveuponthingsgoingidleandstartclearing
//themout.
if(DEBUG_PAUSE)Slog.v(TAG,"Tomanypendingstops,forcingidle");
Messagemsg=Message.obtain();
msg.what=IDLE_NOW_MSG;
mHandler.sendMessage(msg);
}
}
}else{
if(DEBUG_PAUSE)Slog.v(TAG,"Appdiedduringpause,notstopping:"+prev);
prev=null;
}
mPausingActivity=null;
}
if(!mService.mSleeping&&!mService.mShuttingDown){
resumeTopActivityLocked(prev);
}else{
if(mGoingToSleep.isHeld()){
mGoingToSleep.release();
}
if(mService.mShuttingDown){
mService.notifyAll();
}
}
}21 ActivityStack.resumeActivityLocked
此时mResumeAcitivity为空,并且未启动新的app进程,执行startSpecificActivityLocked
finalbooleanresumeTopActivityLocked(ActivityRecordprev){
...
if(mResumedActivity!=null){
if(DEBUG_SWITCH)Slog.v(TAG,"Skipresume:needtostartpausing");
startPausingLocked(userLeaving,false);
returntrue;
}
if(next.app!=null&&next.app.thread!=null){
...
next.app.thread.scheduleResumeActivity(next,
mService.isNextTransitionForward());
pauseIfSleepingLocked();
...
}else{
startSpecificActivityLocked(next,true,false);
returntrue;
}
}22 ActivityStack.startSpecificActivityLocked
根据应用进程名称和用户id(每个activity相对应)启动Activity,如果不存在创建相应进程,根Activity在此处初次创建进程
privatefinalvoidstartSpecificActivityLocked(ActivityRecordr,
booleanandResume,booleancheckConfig){
//Isthisactivity'sapplicationalreadyrunning?
Proce***ecordapp=mService.getProce***ecordLocked(r.processName,
r.info.applicationInfo.uid);
...
if(app!=null&&app.thread!=null){
try{
realStartActivityLocked(r,app,andResume,checkConfig);
return;
}catch(RemoteExceptione){
Slog.w(TAG,"Exceptionwhenstartingactivity"
+r.intent.getComponent().flattenToShortString(),e);
}
//Ifadeadobjectexceptionwasthrown--fallthroughto
//restarttheapplication.
}
mService.startProcessLocked(r.processName,r.info.applicationInfo,true,0,
"activity",r.intent.getComponent(),false);
}
23 ActivityManagerService.startProcessLocked
newProce***ecordLocked 保存进程对应record
重载函数创建进程
发送PROC_START_TIMEOUT_MSG 新进程要求20毫秒内启动完成 否则超时
Process.start
privatefinalvoidstartProcessLocked(Proce***ecordapp,
StringhostingType,StringhostingNameStr){
...
intpid=Process.start("android.app.ActivityThread",
mSimpleProcessManagement?app.processName:null,uid,uid,
gids,debugFlags,null);
if(pid==0||pid==MY_PID){
//Processesarebeingemulatedwiththreads.
app.pid=MY_PID;
app.removed=false;
mStartingProcesses.add(app);
}elseif(pid>0){
app.pid=pid;
app.removed=false;
synchronized(mPidsSelfLocked){
this.mPidsSelfLocked.put(pid,app);
Messagemsg=mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
msg.obj=app;
mHandler.sendMessageDelayed(msg,PROC_START_TIMEOUT);
}
}else{
app.pid=0;
RuntimeExceptione=newRuntimeException(
"Failurestartingprocess"+app.processName
+":returnedpid="+pid);
Slog.e(TAG,e.getMessage(),e);
}
...
}新应用进程启动24 ActivityThread.main
main方法-looper.prepare-thread.attach-looper.loop-thread.detach
thread为ActivityThread,内部初始化ApplicationThread(binder本地对象,ActivityManagerService通信)
publicstaticfinalvoidmain(String[]args){
SamplingProfilerIntegration.start();
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
if(sMainThreadHandler==null){
sMainThreadHandler=newHandler();
}
ActivityThreadthread=newActivityThread();
thread.attach(false);
if(false){
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG,"ActivityThread"));
}
Looper.loop();
if(Process.supportsProcesses()){
thrownewRuntimeException("Mainthreadloopunexpectedlyexited");
}
thread.detach();
Stringname=(thread.mInitialApplication!=null)
?thread.mInitialApplication.getPackageName()
:"<unknown>";
Slog.i(TAG,"Mainthreadof"+name+"isnowexiting");
}25 ActivityThread.attachApplication
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();
}
26 ActivityManagerService.attachApplicationpublicfinalvoidattachApplication(IApplicationThreadthread){
synchronized(this){
intcallingPid=Binder.getCallingPid();
finallongorigId=Binder.clearCallingIdentity();
attachApplicationLocked(thread,callingPid);
Binder.restoreCallingIdentity(origId);
}
}27 ActivityManagerService attachApplicationLocked
使Proce***ecord.thread指向IApplicationThread(IPC),ActivityManagerService 即可以通过该对象与app进行通信
进程启动完成 移除超时msg
获取顶端 ActivityRecord,realStartActivityLocked
privatefinalbooleanattachApplicationLocked(IApplicationThreadthread,
intpid){
Proce***ecordapp;
...
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;
mHandler.removeMessages(PROC_START_TIMEOUT_MSG,app);
...
//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){
Slog.w(TAG,"Exceptioninnewapplicationwhenstartingactivity"
+hr.intent.getComponent().flattenToShortString(),e);
badApp=true;
}
}else{
mMainStack.ensureActivitiesVisibleLocked(hr,null,processName,0);
}
}
}29 ActivityStack.realStartActivityLocked
finalbooleanrealStartActivityLocked(ActivityRecordr,
Proce***ecordapp,booleanandResume,booleancheckConfig)
throwsRemoteException{
...
r.app=app;
if(localLOGV)Slog.v(TAG,"Launching:"+r);
intidx=app.activities.indexOf(r);
if(idx<0){
app.activities.add(r);
}
...
mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
app.thread.scheduleLaunchActivity(newIntent(r.intent),r,
System.identityHashCode(r),
r.info,r.icicle,results,newIntents,!andResume,
mService.isNextTransitionForward());
...
returntrue;
}
ActivityRecord加入app的ac列表
app.thread准备启动ac
(Proce***ecord.thread指向IApplicationThread(IPC),ActivityManagerService 即可以通过该对象与app进行通信)
29 ApplicationThreadNative.scheduleLaunchActivitypublicfinalvoidscheduleLaunchActivity(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();
}主线程启动Activity30 ActivityThread.ApplicationThread.scheduleLaunchActivity
//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);
}
封装ActivityClientRecord信息,主线程LAUNCH_ACTIVITY
31ActivityThread.queueOrSendMessage32 HandleMsgpublicvoidhandleMessage(Messagemsg){
if(DEBUG_MESSAGES)Slog.v(TAG,">>>handling:"+msg.what);
switch(msg.what){
caseLAUNCH_ACTIVITY:{
ActivityClientRecordr=(ActivityClientRecord)msg.obj;
r.packageInfo=getPackageInfoNoCheck(
r.activityInfo.applicationInfo);
handleLaunchActivity(r,null);
}break;
}
}
getPackageInfoNoCheck,返回LoadedApk 已加载的apk信息
把它赋予ActivityClientRecord
33 handleLaunchActivityprivatefinalvoidhandleLaunchActivity(ActivityClientRecordr,IntentcustomIntent){
//Ifwearegettingreadytogcaftergoingtothebackground,well
//wearebackactivesoskipit.
unscheduleGcIdler();
if(localLOGV)Slog.v(
TAG,"Handlinglaunchof"+r);
Activitya=performLaunchActivity(r,customIntent);
if(a!=null){
r.createdConfig=newConfiguration(mConfiguration);
BundleoldState=r.state;
handleResumeActivity(r.token,false,r.isForward);
...
}34 performLaunchActivity
初始化context和application
mInstrumentation.callActivityOnCreate启动activity并恢复状态
mActivities.put(r.token, r); 将toke和ActivityClientRecord对应保存
注意:ActivityClientRecord的token是Binder代理对象,指向ActivityManagerService中的ActivityRecord,双方只是在不同进程使用。
privatefinalActivityperformLaunchActivity(ActivityClientRecordr,IntentcustomIntent){
//System.out.println("#####["+System.currentTimeMillis()+"]ActivityThread.performLaunchActivity("+r+")");
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){
if(!mInstrumentation.onException(activity,e)){
thrownewRuntimeException(
"Unabletoinstantiateactivity"+component
+":"+e.toString(),e);
}
}
try{
Applicationapp=r.packageInfo.makeApplication(false,mInstrumentation);
。。。
mInstrumentation.callActivityOnCreate(activity,r.state);
...35 MainActivity.onCreate
来到大家最熟悉的方法了,流程完结。
总结
1、Launcher组件、MainActivity组件、AMS(ActivityManagerService),这三者的交互为核心,而这三者分属不同进程,以Binder作为通信工具进行交互。
2、主流程:Launcher通知AMS并等待启动——AMS准备启动MainActivity——创建新进程——AMS通知新进程ActivityThread启动MainActivity
3、ActivityManagerNative通过ServiceManager获得AMS的代理对象,实现应用与AMS通信;AMS通过ApplicationThreadProxy获取Launcher代理对象,实现AMS与应用通信。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。