android进阶(九)-----Android四大组件的工作过程

103 阅读2分钟

一、四大组件的运行状态

android四大组件中国除了BroadcastReceiver以外,其他三种都必须在AndroidManifest中注册,对于BroadcastReceiver既可以在AndroidManifest中注册也可以通过代码注册。

在调用方式上,activity、service和BroadcastReceiver需要借助Intent,而ContentProvider则无须借助Intent

二、Activity的工作过程

Activity是一个很重要的组件,启动Activity很简单,只需要

Intent intent = new Intent(this,MainActivity.class); startActivity(intent);

startActivity方法有很多种重载方式,但是最终都会调用startActivityForResult方法,他的实现如下:

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { 
    if (mParent == null) { 
        options = transferSpringboardActivityOptions(options); 
        Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); 
        if (ar != null) { 
            mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); 
        } 
        if (requestCode >= 0) { 
            // If this start is requesting a result, we can avoid making 
            // the activity visible until the result is received. Setting 
            // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the 
            // activity hidden during this time, to avoid flickering. 
            // This can only be done when a result is requested because 
            // that guarantees we will get information back when the 
            // activity is finished, no matter what happens to it. mStartedActivity = true; 
        }   
        cancelInputsAndStartExitTransition(options); 
        // TODO Consider clearing/flushing other event sources and events for child windows. 
    } else { 
        if (options != null) { 
            mParent.startActivityFromChild(this, intent, requestCode, options); 
        } else { 
            // Note we want to go through this method for compatibility with 
            // existing applications that may have overridden it. m           
            Parent.startActivityFromChild(this, intent, requestCode); 
        } 
    } 
}

上面代码中,需要注意mMainThread.getApplicationThread()这个参数,他的类型是ApplicationThread,ApplicationThread是ActivityThread的一个内部类,接着看一下mInstrumentation.execStartActivity方法

public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { 
    IApplicationThread whoThread = (IApplicationThread) contextThread; 
    Uri referrer = target != null ? target.onProvideReferrer() : null; 
    if (referrer != null) { 
        intent.putExtra(Intent.EXTRA_REFERRER, referrer); 
    } 
    if (mActivityMonitors != null) { 
        synchronized (mSync) { 
            final int N = mActivityMonitors.size(); 
            for (int i=0; i<N; i++) { 
                final ActivityMonitor am = mActivityMonitors.get(i); 
                ActivityResult result = null; 
                if (am.ignoreMatchingSpecificIntents()) { 
                    result = am.onStartActivity(intent); 
                } 
                if (result != null) { 
                    am.mHits++; return result; 
                } else if (am.match(who, null, intent)) { 
                    am.mHits++; 
                    if (am.isBlocking()) { 
                        return requestCode >= 0 ? am.getResult() : null; 
                    } 
                    break; 
                } 
            } 
        } 
    } 
    try { 
        intent.migrateExtraStreamToClipData(); 
        intent.prepareToLeaveProcess(who); 
        int result = ActivityManager.getService().startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); 
        checkStartActivityResult(result, intent); 
    } catch (RemoteException e) { 
        throw new RuntimeException("Failure from system", e); 
    } 
    return null; 
}

通过上面代码可以看出,启动Activity真正的实现由ActivityManager.getService()startActivity来完成。

checkStartActivityResult的作用很明显就是检查启动activity的结果

下面分析一下AMS的startActivity方法,如下所示

public final int startActivity(IApplicationThread caller,String callingPackage,Intent intent,String resolvedType,IBinder resultTo,String resultWho,int requestCode,int startFlags,ProfilerInfo profilerInfo,Bundle options){ 
    return startActivityAsUser(caller,callingPackage,intent,resolvedType,resultTo,resultWho,requestCode,startFlags,profilerInfo,options,UserHandle.getCallingUserId()); 
} 
public final int startActivityAsUser(IApplicationThread caller,String callingPackage,Intent intent,String resolvedType,IBinder resultTo,String resultWho,int requestCode,int startFlags,ProfilerInfo profilerInfo,Bundle options,int userId){ 
    enforceNotIsolatedCaller("startActivity"); 
    userId = handleIncomingUser(Binder.getCallingPid(),Binder.getCallingUid(),userId,false,ALLOW_FULL_ONLY,"startActivity",null); 
    return mStackSupervisor.startActivityMayWait(caller,-1,callingPackage,intent,resolvedType,null,null,resultTo,resultWho,requestCode,startFlags,profilerInfo,null,null,options,userId,null,null); 
}

可以看出,Activity的启动过程又转移到了ActivityStackSupervisor的startActivityMayWait方法中了,在startActivityMayWait中又调用了startActivityLocked方法,然后startActivityLocked方法有调用了startActivityUncheckedLocked方法,接着startActivityUncheckedLocked又调用了ActivityStack的resumeTopActivitiesLocked方法,这个时候启动过程已经从ActivityStackSupervisor转移到ActivityStack。

ActivityStack的resumeTopActivitiesLocked方法如下所示:

final boolean resumeTopActivityLocked(ActivityRecord prev,Bundle options){ 
    if(inResumeTopActivity){ 
        return false; 
    } 
    boolean result = false; 
    try{ 
        inResumeTopActivity = true; 
        result = resumeTopActivityInnerLocked(prev,options); 
    }finally{ 
        inResumeTopActivity = false; 
    } 
    return result; 
}

从上面代码可以看出,resumeTopActivityLocked调用了resumeTopActivityInnerLocked方法,resumeTopActivityInnerLocked又调用了ActivityStackSupervisor的startSpecificActivityLoaked方法,startSpecificActivityLoaked的源码如下所示:

void startSpecificActivityLocked(ActivityRecord r,boolean andResume,boolean checkConfig){ 
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,r.info.applicationInfo.uid,true); 
    t.task.stack.setLaunchTime(r); 
    if(app != null && app.thread != null){ 
        try{ 
            if((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS)==0 || !"android".equals(r.info.packageName)){ 
                app.addPackage(r.info.packageName,r.info.applicationInfo.versionCode,mService.mProcessStats); 
            } 
            realStartActivityLocked(r,app,andResume,checkConfig); 
            return; 
        }catch(RemoteException e){
        } 
    } 
    mService.startProcessLocked(r.proessName,r.info.applicationInfo,true,0,"activity",r.intent.getComponent(),false,false,true); 
}