Android应用启动流程

313 阅读2分钟

基于Android 8.0
作为一个应用层开发者,掌握应用启动流程是必须的。

如图当我们点击QQ的图标时,Launcher会调用startActivity()然后经过一系列操作最终启动QQ。从Launcher调用startActivity()到启动QQ这个过程,是今天要分析的。

Launcher请求AMS

在中国几乎每个厂商都有自己的Launcher,它们和原生系统比,在实现细节上可能不同,但大体流程都是一样的。

Launcher请求AMS的过程,从Binder机制角度来看,属于获取服务 和 发送数据过程.

//Launcher.java  这个类继承了 Activity
startActivitySafely{
    ...
   startActivity(intent ,optsBundle);
    ...
}
//Activity.java
startActivityForResult{
    ...
    Instrumentation.execStartActivity();
    ...
}
//Instrumentation.java  这个类主要用于监控应用程序和系统的交互。
execStartActivity{
    ...
    ActivityManager.getService() //Binder机制角度分析 获取服务:Launcher获取AMS服务。注册服务:AMS已经注册好了
    //AIDL角度分析 得到AMS的代理对象,8.0之前是通过AMN.getDefault得到代理对象
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);//Bind机制角度分析  发送请求。
                        //最终调用的是AMS的startActivity方法。在此将处理逻辑交给AMS,实现跨进程通信
    ...
}
//ActivityManager.java
getService{
    //AIDL的形式,8.0之前用的不是AIDL
    return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                //获得AMS的引用
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

AMS请求Zygote创建应用进程

创建应用进程


//ActivityManagerService.java
startActivity{
    ...
    startActivityAsUser()
    ...
}
startActivityAsUser(){
    ...
    mActivityStarter.startActivityMayWait();
    ...
}; 

//ActivityStarter.java   Android 7.0新加的类,加载Activity的控制类。并将Activity和Task和Stack相关联。
startActivityMayWait{
    ...
    startActivity()
    ...
}
startActivity(){
    ...
    startActivityUnchecked();
    ...    
    }
startActivityUnchecked{
    ...
    ActivityStackSupervisor.resumeFocusedStackTopActivityLocked();
    ...
}

//ActivityStackSupervisor.java
resumeFocusedStackTopActivityLocked{
    ...
    ActivityStack.resumeTopActivityUncheckedLocked()
    ...
}

//ActivityStack.java
resumeTopActivityUncheckedLocked{
    ...
    ActivityStackSupervisor.startSpecificActivityLocked();
    ...
}

//ActivityStackSupervisor.java
/**
* 若没有需要的Process则创建进程。
*/
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // 当前要启动Activity 所在的进程
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);
    r.task.stack.setLaunchTime(r);
    if (app != null && app.thread != null) {// 如果进程已经运行
        ... 
        realStartActivityLocked();
    }
    //启动新进程
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}
realStartActivityLocked(){
    ...
    app.thread.scheduleLaunchActivity();
    //app.thread实现的是 IApplicationThread。
    //通过binder通信。也就是说ApplicationThread是SystemServer进程和APP进程的
    //通信桥梁 至此代码逻辑运行到APP进程中。
    ...
}

//Process.java
start(){
    startViaZygote()
}
startViaZygote(){
    zygoteSendArgsAndGetResult()
}
zygoteSendArgsAndGetResult(){
    ...
    openZygoteSocketIfNeeded(){
        ...//向Zygote发起请求
    }
    // 等待 socket 服务端(Zygote)返回新创建的进程pid;
    ...
}

Zygote创建进程

ActivityThread启动Activity

ActivityThread启动Activity

ApplicationThread是ActivityThread的内部类

ApplicationThread
scheduleLaunchActivity{
    sendMessage();
}
ActivityThread.java
sendMessage{
    mH.sendMessage();  //mH是ActivityThread的内部类并继承自Handler
    //ApplicationThread是一个Binder,运行在Binder线程池中。所以需要Handler进行线程切换
  }
handleLaunchActivity{
    performLaunchActivity(){
        //创建Activity的上下文环境
        Instrumenttation.newActivity()  //使用类加载器来创建Activity的实例
        //创建Application
        //初始化Activity  
        //Activity.attach()  attach会创建Windows对象(PhoneWindow);
        //Activity.performCreate();                //此方法会调用Activity的onCreate方法。至此启动过程完成。
    }
 }

H
sendMessage{
    handleLaunchActivity();
}