Android进阶之路

ActivityManagerService流程

2017-11-22  本文已影响134人  xiabodan

Activity启动流程

目的:

一、理清activity的生命周期管理与AMS之间的关系

1、Launcher通知AMS启动某个activity:

Launcher中:应用程序中开启一个activity通过startActivitySafely()---->startActivity(),如果是程序内部启动那么直接调用Activity中的startActivity(),被启动的activity的参数包含在intent中,intent中的参数来自于.xml
文件,--->startActivityForResult()----> mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options),其中Instrumentation是用来监控应用程序与系统之间的交互,其中mMainThread是ActivityThread类的实例,.getApplicationThread()用于获取内部的ApplicationThread的Binder对象(此处有疑问??);----->ActivityManagerNative.getDefault()
.startActivity(), .getDefault()通过ServerManager获取AMS的代理对象"activity",代码如下:

//ActivityManagerNative.java
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
            IBinder b = ServiceManager.getService("activity"); //获取代理对象
            if (false) {
               Log.v("ActivityManager", "default service binder = " + b);
            }
            IActivityManager am = asInterface(b);
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
           return am;
        }
};

接着调用他的方法startActivity()通知AMS启动相应的Activity,这里已经是binder通讯了。

startActivitySafely()    <-----------------Launcher中,如果是在Launcher中点击,从这一步开始
        |
startActivity()          <-----------------Activity中,如果是程序中调用,从这一步开始
    |
startActivityForResult() <-----------------Activity中
    |
mInstrumentation.execStartActivity()  <----------Instrumentation中
    |
ActivityManagerNative.getDefault().startActivity()<----------AMS的proxy
    |
    ...binder...    Launcher--->AMS: Launcher请求启动activity
    |
startActivity()    ---------->通知AMS的Stub中startActivity(),即ActivityManagerService.java中的

至此Launcher中暂时结束!即Launcher进程会------>请求AMS启动一个activity,具体是哪一个activity,看intent

2、AMS保存将要启动的mainactivity,并且AMS处理Launcher向AMS发送的binder消息:START_ACTIVITY_TRANSACTION

startActivity()                     ------->AMS   
    |
startActivityAsUser()               ------->AMS
    |
mStackSupervisor.startActivityMayWait() ------->ActivityStackSupervisor.java 
    |
startActivityLocked()           ------->ActivityStackSupervisor.java      
    |
startActivityUncheckedLocked()
    |
resumeTopActivitiesLocked(targetStack, null, options)  ----->ActivityStack.java
    |
startPausingLocked()                ----->ActivityStack.java
    |
prev.app.thread.schedulePauseActivity() ----->ActivityStack.java   Proxy
    |
    ...binder...    AMS--->Launcher: AMS请求Launcher Pause
    |
schedulePauseActivity()         ------>ActivityThread.java   Stub  

//ActivityThread.java
public final void schedulePauseActivity(IBinder token, boolean finished,
          boolean userLeaving, int configChanges, boolean dontReport) {
     sendMessage(
             finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
             token,
             (userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
             configChanges);
}

3、Launcher收到Pause请求后的动作,并回复AMS(通过AMS的proxy)

schedulePauseActivity()         ------>ActivityThread.java   Stub  
    |
sendMessage()               ------>ActivityThread.java  果然这里是消息处理机制实现
    |
handleMessage(Message msg)      ------>ActivityThread.java  
    |   
handlePauseActivity()
    |
performPauseActivity(token, finished, r.isPreHoneycomb());   ------>ActivityThread.java  
ActivityManagerNative.getDefault().activityPaused(token)     ------>ActivityThread.java  AMS proxy
    |
    ...binder...    Launcher--->AMS : Launcher告知AMS,Launcher已经Pause
    |
activityPaused(token)           ------>AMS Stub

疑问:

4、AMS中处理Launcher发来的Paused通讯请求,并做相应处理

activityPaused(token)           ------>AMS Stub
    |
activityPausedLocked()          ------>ActivityStack.java
    |
completePauseLocked(true)
    |
finishCurrentActivityLocked()
    |
resumeTopActivityLocked()
    |
resumeTopActivityInnerLocked()
    |
startSpecificActivityLocked()       ------->ActivityStackSupervisor.java
    |
startProcessLocked()            ------->AMS
    |
startProcessLocked()            ------->重载的函数,  AMS (如果进程不在的话)
//AMS  startProcessLocked()
checkTime(startTime, "startProcess: asking zygote to start proc");
Process.ProcessStartResult startResult = Process.start(entryPoint,
        app.processName, uid, uid, gids, debugFlags, mountExternal,
        app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
        app.info.dataDir, entryPointArgs);
checkTime(startTime, "startProcess: returned from zygote!");
    |
try {
    return startViaZygote(processClass, niceName, uid, gid, gids,
        debugFlags, mountExternal, targetSdkVersion, seInfo,
        abi, instructionSet, appDataDir, zygoteArgs);
} 
    |
zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote)
    |
通知zygote孵化出新的虚拟机应用程序,并返回PID给AMS,新的应用程序启动起来之后就会进入ActivityThread的main方法中。

至此,AMS就调用Process类创建了一个新的应用程序。并且,该进程的入口函数为main函数,接下来就是新的应用程序进程的工作了。

5、新的应用程序启动之后,会向AMS发送一个启动完成的进程间通讯。

main()                  ------->ActivityThread.java
    |
Looper.prepareMainLooper()  ------->创建消息循环队列,是当前应用进程进入消息循环队列中
ActivityThread thread = new ActivityThread()          创建一个ActivityThread对象  
attach(boolean system)      ------->ActivityThread.java
    |
final IActivityManager mgr = ActivityManagerNative.getDefault();//获取AMS的proxy
mgr.attachApplication(mAppThread)       ----->AMS proxy,调用IActivityManager的接口通讯函数
    |
    ...binder...    ActivityThread--->AMS: APP进程告知AMS启动进程完成
    |
attachApplication(IApplicationThread thread)    ----->AMS Stub
    |
Looper.loop()   

至此,新的应用程序进程通过调用,thread.attach(false)调用attach()函数来向AMS的proxy发送一个进程间通讯回复ATTACH_APPLICATION_TRANSACTION:告诉AMS新的应用程序已经启动完成。

6、 AMS将2步中保存的MainActivity信息,发送给第4步中创建的新应用程序,,以便它可以将MainActivity启动起来

attachApplication(IApplicationThread thread)    ----->AMS Stub
    |
attachApplicationLocked(IApplicationThread thread, int pid) ----->AMS 
    |
attachApplicationLocked(ProcessRecord app)  ----->ActivityStackSupervisor.java  重载
    |
realStartActivityLocked(hr, app, true, true)    ----->ActivityStackSupervisor.java      
    |
app.thread.scheduleLaunchActivity()     ----->ActivityThread proxy
    |
    ...binder...    AMS--->ActivityThread: AMS将MainActivity信息发送新进程
    |
scheduleLaunchActivity()            ----->ActivityThread Stub

至此,AMS向ActivityThread发送进程间通讯SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION

7、应用程序中执行最后工作

scheduleLaunchActivity()            ----->ActivityThread Stub
    |
sendMessage(H.LAUNCH_ACTIVITY, r)       
    |
handleMessage(Message msg)
    |
handleLaunchActivity(r, null)
    |
Activity a = performLaunchActivity(r, customIntent)
    |
mInstrumentation.callActivityOnCreate(activity, r.state)  ------->Instrumentation.java
    |
activity.performCreate(icicle)
    |
onCreate(icicle)        ------>Activity.java
    |
protected void onCreate(@Nullable Bundle savedInstanceState) 

APP中继承的OnCreate()就被调用起来了,最后一步将Activity对象activity启动起来了

注意:

1、mainActivity组件是由Launcher组件启动的,Launcher组件又是通过AMS来启动mainActivity的,因此会涉及到三个进程之间的binder通讯
2、AMS启动是和PMS一样,都在systemServer进程中启动起来的,startBootstrapServices()函数中。
3、还得理清楚ActivityManagerService.java,ActivityManagerNative.java,IActivityManager.java之间的关系

  1. ActivityManagerService.java毋庸置疑肯定是Activity栈管理实现
  2. ActivityManagerNative.java根据代码看,应该是BnXXXX和BpXXXX,也就是binder本地和代理,ActivityManagerService里面才是真正的物理实现。所有的通讯都是通过ActivityManagerNative处理的
  3. IActivityManager.java当然是接口类,ActivityManagerNative实现IActivityManager。

总结,问题:

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        // Initialize before creating the activity
        WindowManagerGlobal.initialize();

        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);   // launch之后紧接着调用ResumeActivity

            if (!r.activity.mFinished && r.startsNotResumed) {
                performPauseActivityIfNeeded(r, reason);
                if (r.isPreHoneycomb()) {
                    r.state = oldState;
                }
            }
        }
    }

...

上一篇下一篇

猜你喜欢

热点阅读