app启动过程及生命周期调用

[TOC]

涉及角色

  • launcher程序:手机桌面app
  • AMS:负责四大组件的启动,管理
  • Zgyote进程:进程孵化器,作为socket的server端接收进程创建请求。持有虚拟机实例,创建的进程都fork自Zgyote进程

app进程启动过程

  • 点击屏幕应用程序图标,触发launcher程序事件,launcher通过Binder请求AMS
  • AMS通过Socket请求Zgyote
  • Zgyote创建进程,调用进程中ActivityThread类的main函数

这时app进程已经起来了

app创建

App进程ActivityThread中:

    public static void main(String[] args) {
        ...
        Process.setArgV0("");
        //创建进程主线程的Looper对象并调用prepare()函数
        Looper.prepareMainLooper();

        //位置1 包括了application等的创建
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        //获取主线程的Handler对象H,处理所有消息
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        Looper.loop();
        ...
    }
    
    //位置1
    private void attach(boolean system, long startSeq) {
        /*
        获取AMS的Binder对象,然后获取远程接口代理
        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
        final IActivityManager am = IActivityManager.Stub.asInterface(b);
        */
        final IActivityManager mgr = ActivityManager.getService();
        /*
        调用AMS的attachApplication方法
        第一个参数是ApplicationThread对象,这是app进程的Binder对象
        */
        mgr.attachApplication(mAppThread, startSeq);
        BinderInternal.addGcWatcher(new Runnable(){...})
    }
    
//进程的Binder对象    
private class ApplicationThread extends IApplicationThread.Stub {
    ...
    public final void bindApplication(String processName, ...){
        ...
        AppBindData data = new AppBindData();
        data.processName = processName;
        ...
        sendMessage(H.BIND_APPLICATION, data);        
    }
}    

AMS中:

    public final void attachApplication(IApplicationThread thread, long startSeq) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }
    
    private final boolean attachApplicationLocked(...){
        //保存当前正在运行的进程的完整信息
        ProcessRecord app;
        ...
        //thread即刚才传过来的app进程的远程接口代理,传递到app进程的ActivityThread中去创建Application对象
        thread.bindApplication(processName, ...);
        ...
        //从这里进去发请求创建第一个Activity
        if (normalMode) {
            didSomething = mAtmInternal.attachApplication(...);
        }
    }

app进程ActivityThread中:
AMS通过Binder调用了bindApplication方法,发送了消息H.BIND_APPLICATION

class H extends Handler {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case BIND_APPLICATION:
                AppBindData data = (AppBindData)msg.obj;
                handleBindApplication(data);
                break;
            ...    
    }
}

private void handleBindApplication(AppBindData data) {
    //记录进程开始时间
    Process.setStartTimes(SystemClock.elapsedRealtime(),SystemClock.uptimeMillis())
    //初始化各种配置,包括时区,图片解码器,http代理等
    mConfiguration = new Configuration(data.config);
    ...
    //将进程名从准备初始化改为正式进程名
    Process.setArgV0(data.processName);
    //data.info是LoadedApk对象
    Application app = data.info.makeApplication(data.restrictedBackupMode, null);
    //这个方法中是app.onCreate();即在这回调了Application对象的onCreate
    mInstrumentation.callApplicationOnCreate(app);
    
}

app进程LoadedApk中:
LoadedApk包括了app的文件目录,类加载器等运行需要的元素

public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }

        java.lang.ClassLoader cl = getClassLoader();
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        Application app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
        ...
        return app;
    }

Application创建完成,
接着创建第一个Activity
AMS进程中:

realStartActivityLocked(ActivityRecord r, WindowProcessController proc,boolean andResume, boolean checkConfig){
    // 创建activity的事务
    ClientTransaction clientTransaction=ClientTransaction.obtain(proc.getThread(), r.appToken);
    //r是ActivityRecord对象,管理打开的activity
    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent)...
    ResumeActivityItem.obtain()
    PauseActivityItem.obtain();
    ...
    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
    //这步是调用了app进程的远程接口代理IApplicationThread的方法
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}

app进程ActivityThread中:

private class ApplicationThread extends IApplicationThread.Stub {
    ...
    public void scheduleTransaction(ClientTransaction transaction){
        ActivityThread.this.scheduleTransaction(transaction);
    }
}    

//scheduleTransaction方法在ApplicationThread父类中,于是又回到app进程执行创建第一个Activity的事务
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);

//事务执行是获取添加的callback是LaunchActivityItem

H收到消息后,事务的执行
/**
 * Request to launch an activity.
 * @hide
 */
public class LaunchActivityItem extends ClientTransactionItem {
    public void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {
        ActivityClientRecord r;
        //client是ActivityThread的对象,ClientTransactionHandler是他的父类
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }
    ...
}
又回到ActivityThread
public Activity handleLaunchActivity(ActivityClientRecordr,PendingTransactionActions pendingActions, Intent customIntent) {
        ...
        final Activity a = performLaunchActivity(r, customIntent);
        ...
        return a;
}
    
//activity运行核心类,ActivityClientRecord记录activity的状态配置等
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        ComponentName component = r.intent.getComponent();
        //activity的上下文对象
        ContextImpl appContext = createBaseContextForActivity(r);
        java.lang.ClassLoader cl = appContext.getClassLoader();
        //位置1,创建!
        Activity activity=mInstrumentation.newActivity(cl,component.getClassName(), r.intent);
        activity.attach(...);
        activity.setTheme(theme);
        //这里进去调用了activity的performCreate方法
        mInstrumentation.callActivityOnCreate(activity, r.state);
        return activity;
}

//Instrumentation中,位置1
public Activity newActivity(ClassLoader cl, String className, Intent intent){
    String pkg = intent != null && intent.getComponent() != null? intent.getComponent().getPackageName() : null;
    return getFactory(pkg).instantiateActivity(cl, className, intent);
}

又调用了AppComponmentFactory中,返回了activity实例
return (Activity) cl.loadClass(className).newInstance();

onCreate生命周期的调用已经找到,像LaunchActivityItem触发onCreate一样,ResumeActivityItem,PauseActivityItem触发onResume,onPause。

你可能感兴趣的:(app启动过程及生命周期调用)