美文网首页启动安卓杂烩
Application、Activity的启动流程(9.0)

Application、Activity的启动流程(9.0)

作者: WaterYuan | 来源:发表于2019-11-28 00:21 被阅读0次
    1、通过ActivityThread的静态main()方法创建new ActivityThread()实例,及其成员变量mAppThread = new ApplicationThread()

    android.app.ActivityThread#main
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    Looper.loop();

    2、App进程的ActivityThread#attach通过Binder IPC向system_server进程ActivityManagerService服务发送attachApplication请求

    android.app.ActivityThread#attach
    final IActivityManager mgr = ActivityManager.getService();
    mgr.attachApplication(mAppThread, startSeq);

    3、system_server进程通过Binder IPC向App进程发送bindApplication。

    ApplicationThread收到bindApplication后通过handler发送H.BIND_APPLICATION进而调用ActivityThread#handleBindApplication,创建new Instrumentation()实例
    进而newApplication,调用Application的attach方法、onCreate方法

    com.android.server.am.ActivityManagerService#attachApplicationLocked
    android.app.ActivityThread.ApplicationThread#bindApplication
    android.app.ActivityThread#handleBindApplication
    mInstrumentation = new Instrumentation();
    app = data.info.makeApplication(data.restrictedBackupMode, null);
    mInstrumentation.callApplicationOnCreate(app);

    3.1、newApplication的过程

    android.app.LoadedApk#makeApplication
    ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
    app = mActivityThread.mInstrumentation.newApplication(
    cl, appClass, appContext);

    android.app.Instrumentation#newApplication(java.lang.ClassLoader, java.lang.String, android.content.Context)
    Application app = getFactory(context.getPackageName()).instantiateApplication(cl, className);
    app.attach(context);

    4、Activity的attach()方法执行流程

    android.app.ActivityThread#handleRelaunchActivity
    android.app.ActivityThread#handleRelaunchActivityInner
    android.app.ActivityThread#handleLaunchActivity
    android.app.ActivityThread#performLaunchActivity
    activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
    activity.attach(...)

    android.app.Activity#attach
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mUiThread = Thread.currentThread();
    mMainThread = mActivityThread
    mInstrumentation = instr;

    补充:
    ApplicationThread的作用是:
    实现双向Binder IPC
    private class ApplicationThread extends IApplicationThread.Stub
    App进程向system_server进程的Binder IPC,通过ActivityManager.getService()得到IActivityManager
    system_server进程向App进程的Binder IPC,通过ApplicationThread

    Launcher启动Activity的流程.png

    参考:
    一个APP从启动到主页面显示经历了哪些过程?
    App启动流程涉及到的类介绍
    Android 组件系列 -- Activity 启动流程(9.0)

    相关文章

      网友评论

        本文标题:Application、Activity的启动流程(9.0)

        本文链接:https://www.haomeiwen.com/subject/kxcvwctx.html