【Android Framework (七) 】- ActivityManagerService(AMS)

news2024/11/15 17:38:52

文章目录

  • 知识回顾
    • 启动第一个流程init
    • Zygote的流程
    • system_server
    • ServiceManager
    • Binder
    • Launcher的启动
  • 前言
  • 源码分析
    • 1.AMS的启动. ActivityManagerService.java
    • 2.setSystemProcess
    • 3.应用进程的初始化
    • 4.Activity的启动流程
  • 拓展知识
    • 1.介绍一下Activity的启动流程。
    • 2.ActivityManagerService在创建应用的时候为什么使用socket 而不是用Binder呢?
    • 3.学习activity可以应用场景比如插件化的核心原理?
  • 总结


知识回顾

启动第一个流程init

1,挂载文件系统,创建文件目录 调用selinux_setup权限安全相关
2,初始化内存空间 初始化属性服务 创建Epoll 注册监听子进程重启异常操作等,对子进程进行线程守护
3,startPropertyServic 开启属性服务 进行监听
4,LoadBootScripts 加载init.rc文件 进行解析 调用do_class_start 文件开启service
5,Service::Start函数->fork子进程->并且执行app_process文件,开启了zygote

Zygote的流程

1,startVm函数注册jvm startReg函数注册jni环境唤起 Zygote.main
2,forkSystemServer
3,preload预加载class 系统资源
4,调用runSelectLoop函数循环等待客户端连接
5,有客户端的连接后调用processOneCommand()函数 fork进程,初始化进程,创建ProcessState初始化binder
6,根据请求的targetClass 执行Main函数

system_server

system_server是系统用来启动管理service的入口,比如我们常用的AMS、WMS、PMS等等都是它来创建的,system_server加载了framework-res.apk,接着调用startBootstrapServices、startCoreServices、startOtherServices开启了非常多的服务,以及开启了WatchDog监控service。

ServiceManager

它是一个服务的提供者,可以让应用获取到系统的各种服务,还有Binder机制。ServiceManager是Android系统为开发者提供的一个服务大管家,当开机之后,由内核态进入用户态之后,会启动system_server进程,在该进程里面会对AMS,PKMS,PMS等等进行创建。然后添加到ServiceManager中。SystemServer算是一个大管家,他整合了系统的各种服务,监控着我们服务,管理服务的周期。而ServiceManager只有一个功能就是提供binder通信,让应用可以获取到系统提供的服务。

Binder

是Android特有的一种通信方式。Android Binder的前身是OpenBinder,后来在OpenBinder的基础上开发了Android Binder。
Android基于Linux所以支持Linux原生的IPC通信机制:共享内存、Pipe、Socket。Binder是Android特有的。

性能上:稳定性: 安全:
Binder : 一次拷贝 c/s架构 客户端和服务端 稳定 内核层校验系统来保证通信安全
共享内存:0次 不稳定会有同步问题和并发死锁问题 自定义协议
管道pipe:需要两次拷贝 单管道 效率低只能读或者只能写 自定义协议
Socket:两次拷贝 c/s架构 不好的地方消耗性能握手和挥手 自定义协议

Launcher的启动

它是由system_server开启的,通过LauncherModel进行IPC通信(Binder)调用PackageManagerService的queryIntentActivities获取到所有应用的信息,然后绑定数据源到RecyclerView中,而它的点击事件则是通过ItemClickHandler来进行分发的

前言

ActivityManagerService,它是Android系统的核心,它管理了系统的四大组件:Activity、Service、ContentProvider、Broadcast。它除了管理四大组件外,同时也负责管理和调度所有的进程。


源码分析

1.AMS的启动. ActivityManagerService.java

AMS是运行在system_server,通过反射构建了ActivityManagerService.Lifecycle对象,初始化了管理四大组件的对象以及一些服务。然后调用setSystemProcess,在systemProcess中,又注册了一些服务,获取到了当前的ApplicationInfo对象,然后把ApplicationInfo转换成ProcessRecord对象,添加到AMS的mPidsSelfLocked管理中。接着在system_server的startOtherServices中调用了systemReady,在systemReady中,调用了ATMS(ActivityTaskManagerService)的onSystemReady,以及AppopsService、UserController进行初始化工作,接着从mPidsSelfLocked集合中查找非FLAG_PERSISTENT标志的进程,并且进行清理。开启需要开机启动的应用( android:persistent),接着开启Launcher,发送ACTION_USER_STARTED和ACTION_USER_STARTING广播。

稍后我们在创建进程的时候会接触到这个集合。这个标记就和PMS相关了,我们之前没有介绍,简单看一下就是在updatePackagesIfNeeded . getPackagesForDexopt的方法中发送一个ACTION_PRE_BOOT_COMPLETED的广播,如果应用相应这个广播并且加入FLAG_PERSISTENT标志,就可以存活下来。对接收这个广播的package加载要优先于systemReady,也就是优先其他package的加载。用于开机优先打开的app flag_persistent/

文件目录:/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private void startBootstrapServices() {
//……………………
//创建ActivityTaskManagerService  ActivityManagerService 并关联     mSystemServiceManager installer
ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//将服务添加到ServiceManager
mActivityManagerService.setSystemProcess();
//……………………
}

public Lifecycle(Context context) {
    super(context);
    //创建了AMS的实例
    mService = new ActivityManagerService(context, sAtm);
}

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector();
    mContext = systemContext;//设置context 这里的context 不是我们应用的context是framework-res.apk

    mFactoryTest = FactoryTest.getMode();
    //获取system_server中的ActivityThread
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
    //创建处理消息的线程和Handler
    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = mInjector.getUiHandler(this);
       
    //创建管理广播的队列 前台和后台
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", foreConstants, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", backConstants, true);
    mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
            "offload", offloadConstants, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;
    mBroadcastQueues[2] = mOffloadBroadcastQueue;
    //管理service的对象
    mServices = new ActiveServices(this);
    //管理ContentProvider的对象
    mProviderMap = new ProviderMap(this);
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    //获取系统目录
    final File systemDir = SystemServiceManager.ensureSystemDir();
    //创建电池状态管理的service
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
            BackgroundThread.get().getHandler());
     //创建进程状态管理的服务
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
    
    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
    //创建UserController
    mUserController = new UserController(this);

    mPendingIntentController = new PendingIntentController(
            mHandlerThread.getLooper(), mUserController);

    if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
        mUseFifoUiScheduling = true;
    }

    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    //赋值ActivityTaskManagerService
    mActivityTaskManager = atm;
    //进行初始化
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    //创建CPU的统计线程
    mProcessCpuThread = new Thread("CpuTracker") {
        @Override
        public void run() {
            synchronized (mProcessCpuTracker) {
                mProcessCpuInitLatch.countDown();
                mProcessCpuTracker.init();
            }
            while (true) {
                try {
                    try {
                        synchronized(this) {
                            final long now = SystemClock.uptimeMillis();
                            long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
                            long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
                            //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
                            //        + ", write delay=" + nextWriteDelay);
                            if (nextWriteDelay < nextCpuDelay) {
                                nextCpuDelay = nextWriteDelay;
                            }
                            if (nextCpuDelay > 0) {
                                mProcessCpuMutexFree.set(true);
                                this.wait(nextCpuDelay);
                            }
                        }
                    } catch (InterruptedException e) {
                    }
                    updateCpuStatsNow();
                } catch (Exception e) {
                    Slog.e(TAG, "Unexpected exception collecting process stats", e);
                }
            }
        }
    };

    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
    //添加到看门狗 进行检测
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);

    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {
        Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(
                mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
        Slog.w(TAG, "Setting background thread cpuset failed");
    }

}


private void start() {
    removeAllProcessGroups();
    //开启cpu线程
    mProcessCpuThread.start();
    //把电池状态管理添加到ServiceManager中
    mBatteryStatsService.publish();
    //把AppOpsService添加到ServiceManager中
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    mActivityTaskManager.onActivityManagerInternalAdded();
    mUgmInternal.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    // Wait for the synchronized block started in mProcessCpuThread,
    // so that any other access to mProcessCpuTracker from main thread
    // will be blocked during mProcessCpuTracker initialization.
    try {
        mProcessCpuInitLatch.await();
    } catch (InterruptedException e) {
        Slog.wtf(TAG, "Interrupted wait during start", e);
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted wait during start");
    }
}


public static ActivityManagerService startService(
        SystemServiceManager ssm, ActivityTaskManagerService atm) {
    sAtm = atm;
    //反射创建,并添加到mServices中,调用onStart函数
    return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}


private void startOtherServices() {
//……………………
    // 调用 AMS 的 systemReady
    mActivityManagerService.systemReady(...);
}


public void setSystemProcess() {
    try {
    //添加自己到ServiceManager
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
       //添加进程管理服务 可以获取每个进程内存使用情况
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        //添加 MemBinder,是用来dump每个进程内存信息的服务
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        //添加GraphicsBinder 可以获取每个进程图形加速的服务
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        //添加 DbBinder  获取每个进程数据库的服务
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        //权限服务
        ServiceManager.addService("permission", new PermissionController(this));
        //进程相关信息
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //获取到当前的ApplicationInfo 也就是framework-res.apk
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

        synchronized (this) {
        //把system_server添加到AMS的process管理者中
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    new HostingRecord("system"));
            app.setPersistent(true);
            app.pid = MY_PID;
            app.getWindowProcessController().setPid(MY_PID);
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            mPidsSelfLocked.put(app);
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }
    //应用启动的监听
    mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
            new IAppOpsCallback.Stub() {
                @Override public void opChanged(int op, int uid, String packageName) {
                    if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                        if (mAppOpsService.checkOperation(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });
}

2.setSystemProcess

我们知道是通过反射构建了ActivityManagerService.Lifecycle对象,初始化了管理四大组件的对象以及一些服务。然后调用setSystemProcess。

public void setSystemProcess() {
    try {
    //添加自己到ServiceManager
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
       //添加进程管理服务 可以获取每个进程内存使用情况
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        //添加 MemBinder,是用来dump每个进程内存信息的服务
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        //添加GraphicsBinder 可以获取每个进程图形加速的服务
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        //添加 DbBinder  获取每个进程数据库的服务
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        //权限服务
        ServiceManager.addService("permission", new PermissionController(this));
        //进程相关信息
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //获取到当前的ApplicationInfo 也就是framework-res.apk
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

        synchronized (this) {
        //把system_server添加到AMS的process管理者中
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    new HostingRecord("system"));
            app.setPersistent(true);
            app.pid = MY_PID;
            app.getWindowProcessController().setPid(MY_PID);
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            mPidsSelfLocked.put(app);
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }
    //应用启动的监听
    mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
            new IAppOpsCallback.Stub() {
                @Override public void opChanged(int op, int uid, String packageName) {
                    if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                        if (mAppOpsService.checkOperation(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });
}

systemProcess中,又注册了一些服务,获取到了当前的ApplicationInfo对象,然后把ApplicationInfo转换成ProcessRecord对象,添加到AMS的mPidsSelfLocked管理中。接着在system_server的startOtherServices中调用了systemReady。

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    synchronized(this) {
        if (mSystemReady) {
        if (goingCallback != null) {
            goingCallback.run();
        }
        return;
    }
        mLocalDeviceIdleController
                = LocalServices.getService(DeviceIdleController.LocalService.class);
                //调用ActivityTaskManagerService的systemReady 准备和task相关的服务
        mActivityTaskManager.onSystemReady();
        //装载用户Profile的信息
        mUserController.onSystemReady();
        //启动App权限监听
        mAppOpsService.systemReady();
        mSystemReady = true;
    }

    //查找需要kill的进程
    ArrayList<ProcessRecord> procsToKill = null;
    synchronized(mPidsSelfLocked) {
        for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
            ProcessRecord proc = mPidsSelfLocked.valueAt(i);
            //判断进程是否有FLAG_PERSISTENT标志
            if (!isAllowedWhileBooting(proc.info)){
                if (procsToKill == null) {
                    procsToKill = new ArrayList<ProcessRecord>();
                }
                procsToKill.add(proc);
            }
        }
    }

    synchronized(this) {
        if (procsToKill != null) {//清理
            for (int i=procsToKill.size()-1; i>=0; i--) {
                ProcessRecord proc = procsToKill.get(i);
                mProcessList.removeProcessLocked(proc, true, false, "system update done");
            }
        }
        //清理完成
        mProcessesReady = true;
    }
  //………………

    synchronized (this) {
          //开启 开机就需要启动的app
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);

        //开启Launcher
        mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        
 //发送ACTION_USER_STARTED 广播
Intent intent = new Intent(Intent.ACTION_USER_STARTED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
        | Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
        null, null, 0, null, null, null, OP_NONE,
        null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
        currentUserId);
 //发送ACTION_USER_STARTING广播
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
        null, new IIntentReceiver.Stub() {
            @Override
            public void performReceive(Intent intent, int resultCode, String data,
                    Bundle extras, boolean ordered, boolean sticky, int sendingUser)
                    throws RemoteException {
            }
        }, 0, null, null,
        new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
        null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
        UserHandle.USER_ALL);
        }
    }
}

    final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
            boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride) {
        ProcessRecord app;
        // isolated 为 true 表示要启动一个新的进程
        if (!isolated) {
            // 在已经启动的进程列表中查找
            app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
                    info.uid, true);
        } else {
            app = null;
        }

        if (app == null) {
            // 新建一个 ProcessRecord 对象
            app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0,
                    new HostingRecord("added application",
                            customProcess != null ? customProcess : info.processName));
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
        }

        // This package really, really can not be stopped.
        try {
            // 将包的stopped状态设置为false
            // 如果为ture那么所有广播都无法接收,除非带有标记FLAG_INCLUDE_STOPPED_PACKAGES的广播
            // 正经的广播都不会带有这个标记
            AppGlobals.getPackageManager().setPackageStoppedState(
                    info.packageName, false, UserHandle.getUserId(app.uid));
        } catch (RemoteException e) {
        } catch (IllegalArgumentException e) {
            Slog.w(TAG, "Failed trying to unstop package "
                    + info.packageName + ": " + e);
        }

        if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
//            设置persistent标记
            app.setPersistent(true);
            app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
        }
        if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
            mPersistentStartingProcesses.add(app);
            //启动进程
            mProcessList.startProcessLocked(app, new HostingRecord("added application",
                    customProcess != null ? customProcess : app.processName),
                    disableHiddenApiChecks, mountExtStorageFull, abiOverride);
        }

        return app;
    }

3.应用进程的初始化

文件目录:/frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
    AndroidOs.install();
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("<pre-initialized>");
    //准备MainLooper
    Looper.prepareMainLooper();

    long startSeq = 0;
    if (args != null) {
        for (int i = args.length - 1; i >= 0; --i) {
            if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                startSeq = Long.parseLong(
                        args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }
    //创建ActivityThread 之前system_server是通过静态函数systemMain来创建的 现在直接new的,设置了mResourcesManager
    ActivityThread thread = new ActivityThread();
    //调用了attach
    thread.attach(false, startSeq);

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();//开启loop
}

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {//之前system_server 不走这里,现在我们走这里了
    //设置AppName
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                UserHandle.myUserId());
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        final IActivityManager mgr = ActivityManager.getService();
        try {
        //调用AMS的attachApplication 这里又是一次IPC通信 因为我们当前是应用进程了
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    ViewRootImpl.addConfigCallback(configChangedCallback);
}

AMS的attachApplication
public final void attachApplication(IApplicationThread thread, long startSeq) {
    if (thread == null) {
        throw new SecurityException("Invalid application interface");
    }
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        //调用attachApplicationLocked
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}


private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
        int pid, int callingUid, long startSeq) {

    //根据pid获取到app信息
    app = mPidsSelfLocked.get(pid);
    //thread指的是ActivityThread 所以这里是IPC通信
    thread.bindApplication(processName, appInfo, providers,
        instr2.mClass,
        profilerInfo, instr2.mArguments,
        instr2.mWatcher,
        instr2.mUiAutomationConnection, testMode,
        mBinderTransactionTrackingEnabled, enableTrackAllocation,
        isRestrictedBackupMode || !normalMode, app.isPersistent(),
        new Configuration(app.getWindowProcessController().getConfiguration()),
        app.compat, getCommonServicesLocked(app.isolated),
        mCoreSettingsObserver.getCoreSettingsLocked(),
        buildSerial, autofillOptions, contentCaptureOptions);
        
//从starting applications中移除
mPersistentStartingProcesses.remove(app);

    if (normalMode) {
        try {
        //启动activity
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
            checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
            badApp = true;
        }
    }

    return true;
}


//到了ActivityThread的bindApplication
public final void bindApplication(String processName, ApplicationInfo appInfo,
        List<ProviderInfo> providers, ComponentName instrumentationName,
        ProfilerInfo profilerInfo, Bundle instrumentationArgs,
        IInstrumentationWatcher instrumentationWatcher,
        IUiAutomationConnection instrumentationUiConnection, int debugMode,
        boolean enableBinderTracking, boolean trackAllocation,
        boolean isRestrictedBackupMode, boolean persistent, Configuration config,
        CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
        String buildSerial, AutofillOptions autofillOptions,
        ContentCaptureOptions contentCaptureOptions) {
    setCoreSettings(coreSettings);

    AppBindData data = new AppBindData();
    data.processName = processName;
    data.appInfo = appInfo;
    data.providers = providers;
    data.instrumentationName = instrumentationName;
    data.instrumentationArgs = instrumentationArgs;
    data.instrumentationWatcher = instrumentationWatcher;
    data.instrumentationUiAutomationConnection = instrumentationUiConnection;
    data.debugMode = debugMode;
    data.enableBinderTracking = enableBinderTracking;
    data.trackAllocation = trackAllocation;
    data.restrictedBackupMode = isRestrictedBackupMode;
    data.persistent = persistent;
    data.config = config;
    data.compatInfo = compatInfo;
    data.initProfilerInfo = profilerInfo;
    data.buildSerial = buildSerial;
    data.autofillOptions = autofillOptions;
    data.contentCaptureOptions = contentCaptureOptions;
    //给handle 发送BIND_APPLICATION data就是上边的data
    sendMessage(H.BIND_APPLICATION, data);
}
在handleMessage中

case BIND_APPLICATION:
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
    AppBindData data = (AppBindData)msg.obj;
    //调用handleBindApplication
    handleBindApplication(data);
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    break;
    
    
    
private void handleBindApplication(AppBindData data) {
    //把UI线程注册成运行时 敏感线程
    VMRuntime.registerSensitiveThread();

    //记录进程运行时间
    Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
    //设置进程名
    android.ddm.DdmHandleAppName.setAppName(data.processName,
                                            UserHandle.myUserId());
    VMRuntime.setProcessPackageName(data.appInfo.packageName);
    //应用目录
    VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);

    if (mProfiler.profileFd != null) {
        mProfiler.startProfiling();
    }
//获取到loadedApk 并存入到mPackages中
data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);


//创建Instrumentation
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);

    //创建Application
    Application app;
    //创建应用
        app = data.info.makeApplication(data.restrictedBackupMode, null);
        mInitialApplication = app;
        mInstrumentation.onCreate(data.instrumentationArgs);
        mInstrumentation.callApplicationOnCreate(app);
    }
}
//创建Application
public Application makeApplication(boolean forceDefaultAppClass,
        Instrumentation instrumentation) {
    if (mApplication != null) {//如果已经创建过了 返回
        return mApplication;
    }
    Application app = null;
    //拿到applicationName 就是我们配置的Application 默认是android.app.Application
    String appClass = mApplicationInfo.className; 
    if (forceDefaultAppClass || (appClass == null)) {
        appClass = "android.app.Application";
    }
        java.lang.ClassLoader cl = getClassLoader();
        //创建上下文
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        //创建Application
        app = mActivityThread.mInstrumentation.newApplication(
                cl, appClass, appContext);
        appContext.setOuterContext(app);
   //添加到mAllApplications中
    mActivityThread.mAllApplications.add(app);
    mApplication = app;

    if (instrumentation != null) {
    //执行oncreate
            instrumentation.callApplicationOnCreate(app);
    }

    return app;
}



//调用Application的onCreate函数
public void callApplicationOnCreate(Application app) {
    app.onCreate();
}


//Instrumentation中创建application
public Application newApplication(ClassLoader cl, String className, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
    Application app = getFactory(context.getPackageName())
            .instantiateApplication(cl, className);
            //调用Application的attach方法
    app.attach(context);
    return app;
}

//返回AppComponentFactory
private AppComponentFactory getFactory(String pkg) {
    if (pkg == null) {
        Log.e(TAG, "No pkg specified, disabling AppComponentFactory");
        return AppComponentFactory.DEFAULT;
    }
    if (mThread == null) {
        Log.e(TAG, "Uninitialized ActivityThread, likely app-created Instrumentation,"
                + " disabling AppComponentFactory", new Throwable());
        return AppComponentFactory.DEFAULT;
    }
    //之前在handlebindApplication 已经存入了 现在获取出来apk
    LoadedApk apk = mThread.peekPackageInfo(pkg, true);
    if (apk == null) apk = mThread.getSystemContext().mPackageInfo;
    return apk.getAppFactory();
}


文件目录:/frameworks/base/core/java/android/app/AppComponentFactory.java 
//通过反射创建Application
public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
        @NonNull String className)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (Application) cl.loadClass(className).newInstance();
}


final void attach(Context context) {
    attachBaseContext(context);//调用attachBaseContext
    //拿到mLoadedApk
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

4.Activity的启动流程

进程启动之后是如何启动Activity的。首先让我们回到AMS,当ActivityThread创建之后会通知AMS进行attachApplication


private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
        int pid, int callingUid, long startSeq) {

    //根据pid获取到app信息
    app = mPidsSelfLocked.get(pid);
    //thread指的是ActivityThread 所以这里是IPC通信
    thread.bindApplication(processName, appInfo, providers,
        instr2.mClass,
        profilerInfo, instr2.mArguments,
        instr2.mWatcher,
        instr2.mUiAutomationConnection, testMode,
        mBinderTransactionTrackingEnabled, enableTrackAllocation,
        isRestrictedBackupMode || !normalMode, app.isPersistent(),
        new Configuration(app.getWindowProcessController().getConfiguration()),
        app.compat, getCommonServicesLocked(app.isolated),
        mCoreSettingsObserver.getCoreSettingsLocked(),
        buildSerial, autofillOptions, contentCaptureOptions);
        
//从starting applications中移除
mPersistentStartingProcesses.remove(app);

    if (normalMode) {
        try {
        //启动activity
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
            checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
            badApp = true;
        }
    }

    return true;
}
//WindowProcessController 用来和AMS的ProcessRecord进行通信,当ProcessRecord中对应应用进程做出修改之后通过他来和WM进行通信
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
        boolean andResume, boolean checkConfig) throws RemoteException {
    //判断是否都暂停成功
    if (!mRootActivityContainer.allPausedActivitiesComplete()) {
        return false;
    }
    //根据activity 获取到taskRecord
    final TaskRecord task = r.getTaskRecord();
    //获取到ActivityStack
    final ActivityStack stack = task.getStack();

    //resume引用++
    beginDeferResume();

    try {
        r.startFreezingScreenLocked(proc, 0);
        r.startLaunchTickingLocked();
        //设置WPC
        r.setProcess(proc);
        if (andResume && !r.canResumeByCompat()) {
            andResume = false;
        }
          //launchCount++ 记录启动次数
        r.launchCount++;
        //记录启动时间
        r.lastLaunchTime = SystemClock.uptimeMillis();
        //添加activity到WPC
        proc.addActivityIfNeeded(r);
        try {
            //创建ClientTransaction 用来和客户端通信 客户端收到后执行对应的事务
            final ClientTransaction clientTransaction = ClientTransaction.obtain(
            //client为当前应用进程 以及apptoken
                    proc.getThread(), r.appToken);
            //获取到DisplayContent 屏幕显示设备
            final DisplayContent dc = r.getDisplay().mDisplayContent;
            //添加callback 这个会触发onCreate
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                    r.icicle, r.persistentState, results, newIntents,
                    dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                            r.assistToken));
             //创建ActivityLifecycleItem 决定执行resume还是pause
            final ActivityLifecycleItem lifecycleItem;
            if (andResume) {//这里为true
            //设置为on_resume 
                lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            //设置状态请求为resume
            clientTransaction.setLifecycleStateRequest(lifecycleItem);    
 //执行事务           mService.getLifecycleManager().scheduleTransaction(clientTransaction);

        } catch (RemoteException e) {
        }
    } finally {
        endDeferResume();
    }

    r.launchFailed = false;
    if (stack.updateLRUListLocked(r)) {
    }
    if (andResume && readyToResume()) {
        stack.minimalResumeActivityLocked(r);
    } else {
        r.setState(PAUSED, "realStartActivityLocked");
    }
    //oom相关 更新进程的状态信息
    proc.onStartActivity(mService.mTopProcessState, r.info);
    if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
        mService.getActivityStartController().startSetupActivity();
    }
    //更新关心的服务
    if (r.app != null) {
        r.app.updateServiceConnectionActivities();
    }

    return true;
}
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}


文件目录:/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public void schedule() throws RemoteException {
//这里的mClient就是我们的应用进程ActivityThread
    mClient.scheduleTransaction(this);
}

//ActivityThread中 执行的是父类的
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

//执行ClientTransactionHandler的scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
    //执行客户端事务之前需要处理的事务
    transaction.preExecute(this);
    //发送消息给mH执行EXECUTE_TRANSACTION
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

//发送消息给mH
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    Message msg = Message.obtain();
    msg.what = what;
    msg.obj = obj;
    msg.arg1 = arg1;
    msg.arg2 = arg2;
    if (async) {
        msg.setAsynchronous(true);
    }
    mH.sendMessage(msg);
}

看看怎么处理的这个消息.
case EXECUTE_TRANSACTION:
    //拿到ClientTransaction
    final ClientTransaction transaction = (ClientTransaction) msg.obj;
    //调用TransactionExecutor(远程事务的执行者)执行事务
    mTransactionExecutor.execute(transaction);
    if (isSystem()) {
        transaction.recycle();
    }
    break;
    
    //在这里执行事务
public void execute(ClientTransaction transaction) {
    //拿到binder
    final IBinder token = transaction.getActivityToken();
    //执行事务 LaunchActivityItem
    executeCallbacks(transaction);
    //执行状态
    executeLifecycleState(transaction);
    //清空actions
    mPendingActions.clear();
    if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}

//执行事务 也就是LauncherActivityItem的执行 
public void executeCallbacks(ClientTransaction transaction) {
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    //没有callback 返回 我们是有callback的就是LauncherActivityItem
    if (callbacks == null || callbacks.isEmpty()) {
        // No callbacks to execute, return early.
        return;
    }

    final IBinder token = transaction.getActivityToken();
    //获取到ActivityClientRecord 获取到客户端的ActivityRecord
    ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        //执行item的execute item就是LaunchActivityItem
        item.execute(mTransactionHandler, token, mPendingActions);
        //调用postExecute
        item.postExecute(mTransactionHandler, token, mPendingActions);
       
        }
    }
}

//execute 获取到ActivityClientRecord
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
            mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
            mPendingResults, mPendingNewIntents, mIsForward,
            mProfilerInfo, client, mAssistToken);
      //调用ActivityThread的handleLaunchActivity
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}

public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    mSomeActivitiesChanged = true;
    //初始化WMG 之后说WMS的时候在介绍 和window 页面相关的
    WindowManagerGlobal.initialize();
    
    //调用performLaunchActivity
    final Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    } else {
    }

    return a;
}

//创建Activity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //拿到ActivityInfo
    ActivityInfo aInfo = r.activityInfo;
    //拿到component
    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }
    //根据ActivityClientRecord来创建activity context 
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        //获取到类加载器 也就是我们app的类加载器 PathCalssLoader
        java.lang.ClassLoader cl = appContext.getClassLoader();
        //通过mInstrumentation的newActivity  反射创建Activity 
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
    }

    try {
        //获取app
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        
        if (activity != null) {
            //创建Configuration 屏幕大小 屏幕方向 和一些配置的信息
            Configuration config = new Configuration(mCompatConfiguration);
            if (r.overrideConfig != null) {
                config.updateFrom(r.overrideConfig);
            }
            Window window = null;
            if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                window = r.mPendingRemoveWindow;
                r.mPendingRemoveWindow = null;
                r.mPendingRemoveWindowManager = null;
            }
            //设置OuterContext
            appContext.setOuterContext(activity);
            //调用activity的attach window相关
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback,
                    r.assistToken);

            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            r.lastNonConfigurationInstances = null;
            checkAndBlockForNetworkAccess();
            activity.mStartedActivity = false;
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }
            activity.mCalled = false;
            //执行mInstrumentation的callActivityOncreate
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
        }
            r.activity = activity;
        }
        //设置状态为ON_CREATE
        r.setState(ON_CREATE);
        synchronized (mResourcesManager) {
            //存入map
            mActivities.put(r.token, r);
        }

    } catch (SuperNotCalledException e) {
    } catch (Exception e) {
    }
    return activity;
}
//Instrumentation的newActivity
public Activity newActivity(ClassLoader cl, String className,
        Intent intent)
        throws InstantiationException, IllegalAccessException,
        ClassNotFoundException {
    String pkg = intent != null && intent.getComponent() != null
            ? intent.getComponent().getPackageName() : null;
    return getFactory(pkg).instantiateActivity(cl, className, intent);
}
//反射创建Activity 返回
public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
        @Nullable Intent intent)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (Activity) cl.loadClass(className).newInstance();
}

//调用Activity的attach 为Activity关联上下文环境
final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
        //调用attachBaseContext
    attachBaseContext(context);
    //执行fragments的attach
    mFragments.attachHost(null /*parent*/);
    //创建PhoneWindow
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    mWindow.setWindowControllerCallback(this);
    mWindow.setCallback(this);
    mWindow.setOnWindowDismissedCallback(this);
    mWindow.getLayoutInflater().setPrivateFactory(this);
    if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
        mWindow.setSoftInputMode(info.softInputMode);
    }
    if (info.uiOptions != 0) {
        mWindow.setUiOptions(info.uiOptions);
    }
   //设置ui线程
    mUiThread = Thread.currentThread();
    //设置mainThread
    mMainThread = aThread;
   //设置Instrumentation
    mInstrumentation = instr;
    mToken = token;
    mAssistToken = assistToken;
    mIdent = ident;
    mApplication = application;
    mIntent = intent;
    mReferrer = referrer;
    mComponent = intent.getComponent();
    mActivityInfo = info;
    mTitle = title;
    mParent = parent;
    mEmbeddedID = id;
    mLastNonConfigurationInstances = lastNonConfigurationInstances;
    if (voiceInteractor != null) {
        if (lastNonConfigurationInstances != null) {
            mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
        } else {
            mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
                    Looper.myLooper());
        }
    }
    mWindow.setWindowManager(
            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
            mToken, mComponent.flattenToString(),
            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
    if (mParent != null) {
        mWindow.setContainer(mParent.getWindow());
    }
    mWindowManager = mWindow.getWindowManager();
    mCurrentConfig = config;

    mWindow.setColorMode(info.colorMode);

    setAutofillOptions(application.getAutofillOptions());
    setContentCaptureOptions(application.getContentCaptureOptions());
}

//执行activity的OnCreate
public void callActivityOnCreate(Activity activity, Bundle icicle) {
//从waitActivities中移除
    prePerformCreate(activity);
    //执行Activity的生命周期OnCreate
    activity.performCreate(icicle);
    //监控ActivityMonitor
    postPerformCreate(activity);
}

final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
//回调Activity的监听onActivityPreCreated 例如在Application中注册了
    dispatchActivityPreCreated(icicle);
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    //调用onCreate
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
  
    mActivityTransitionState.readState(icicle);
    a
    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
    //Fragments的分发
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    //回调Activity的监听post
    dispatchActivityPostCreated(icicle);
}


//就是我们复写的onCreate
protected void onCreate(@Nullable Bundle savedInstanceState) {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);

    if (mLastNonConfigurationInstances != null) {
        mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
    }
    if (mActivityInfo.parentActivityName != null) {
        if (mActionBar == null) {
            mEnableDefaultActionBarUp = true;
        } else {
            mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
        }
    }
    if (savedInstanceState != null) {
        mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
        mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                View.LAST_APP_AUTOFILL_ID);

        if (mAutoFillResetNeeded) {
            getAutofillManager().onCreate(savedInstanceState);
        }

        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                ? mLastNonConfigurationInstances.fragments : null);
    }
    mFragments.dispatchCreate();
    dispatchActivityCreated(savedInstanceState);
    if (mVoiceInteractor != null) {
        mVoiceInteractor.attachActivity(this);
    }
    mRestoredFromBundle = savedInstanceState != null;
    mCalled = true;
}
private void executeLifecycleState(ClientTransaction transaction) {
//我们之前在这里设置了ResumeActivityItem
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    if (lifecycleItem == null) {
        return;
    }
    final IBinder token = transaction.getActivityToken();
    //获取到ActivityClientRecord
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
     //lifecycleItem是ResumeActivityItem 它的targetState是ON_RESUME
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}



private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
        ClientTransaction transaction) {
        //获取到当前状态是ON_CREATE
    final int start = r.getLifecycleState();
    //数组里面存储的是2
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    //执行lifecyleSequence
    performLifecycleSequence(r, path, transaction);
}


public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
    mLifecycleSequence.clear();
    if (finish >= start) {//当前start是1 finish是3 
        for (int i = start + 1; i <= finish; i++) {
            //添加2和3
            mLifecycleSequence.add(i);
        }
    } else { // finish < start, can't just cycle down
        if (start == ON_PAUSE && finish == ON_RESUME) {
            // Special case when we can just directly go to resumed state.
            mLifecycleSequence.add(ON_RESUME);
        } else if (start <= ON_STOP && finish >= ON_START) {
            // Restart and go to required state.

            // Go to stopped state first.
            for (int i = start + 1; i <= ON_STOP; i++) {
                mLifecycleSequence.add(i);
            }
            // Restart
            mLifecycleSequence.add(ON_RESTART);
            // Go to required state
            for (int i = ON_START; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        } else {
            // Relaunch and go to required state

            // Go to destroyed state first.
            for (int i = start + 1; i <= ON_DESTROY; i++) {
                mLifecycleSequence.add(i);
            }
            // Go to required state
            for (int i = ON_CREATE; i <= finish; i++) {
                mLifecycleSequence.add(i);
            }
        }
    }
    //删除最后一个3
    if (excludeLastState && mLifecycleSequence.size() != 0) {
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }

    return mLifecycleSequence;
}

private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
        ClientTransaction transaction) {
    final int size = path.size();//size = 2
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        switch (state) {
            case ON_START://2
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            case ON_RESUME://3
                mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                        r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                break;
        }
    }
}

//处理startActivity
public void handleStartActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions) {
    final Activity activity = r.activity;
    //执行onStart 分发fragments的onStart 以及监听函数的执行
    activity.performStart("handleStartActivity");
    //设置状态为ON_START
    r.setState(ON_START);
//执行onRestoreInstanceState
    if (pendingActions.shouldRestoreInstanceState()) {
        if (r.isPersistable()) {
            if (r.state != null || r.persistentState != null) {
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                        r.persistentState);
            }
        } else if (r.state != null) {
            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
        }
    }

//执行onPostCreate
    if (pendingActions.shouldCallOnPostCreate()) {
        activity.mCalled = false;
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnPostCreate(activity, r.state,
                    r.persistentState);
        } else {
            mInstrumentation.callActivityOnPostCreate(activity, r.state);
        }
    }
}


final void performStart(String reason) {
    //分发pre start
    dispatchActivityPreStarted();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    mFragments.noteStateNotSaved();
    mCalled = false;
    mFragments.execPendingActions();
    //调用Activity的onStart
    mInstrumentation.callActivityOnStart(this);
    //fragments分发start
    mFragments.dispatchStart();
    mFragments.reportLoaderStart();
    
    boolean isAppDebuggable =
            (mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;

    boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;

    if (isAppDebuggable || isDlwarningEnabled) {
        String dlwarning = getDlWarning();
        if (dlwarning != null) {
            String appName = getApplicationInfo().loadLabel(getPackageManager())
                    .toString();
            String warning = "Detected problems with app native libraries\n" +
                             "(please consult log for detail):\n" + dlwarning;
            if (isAppDebuggable) {//是否debug
                  new AlertDialog.Builder(this).
                      setTitle(appName).
                      setMessage(warning).
                      setPositiveButton(android.R.string.ok, null).
                      setCancelable(false).
                      show();
            } else {
            }
        }
    }
    GraphicsEnvironment.getInstance().showAngleInUseDialogBox(this);
    mActivityTransitionState.enterReady(this);
    //执行post回调
    dispatchActivityPostStarted();
}

//执行activity的onStart
public void callActivityOnStart(Activity activity) {
    activity.onStart();
}

//Activity的onStart
protected void onStart() {
    mCalled = true;
       //分发Fragments
    mFragments.doLoaderStart();
    //分发监听
    dispatchActivityStarted();

    if (mAutoFillResetNeeded) {
        getAutofillManager().onVisibleForAutofill();
    }
}


//执行activity的onPostCreate
public void callActivityOnPostCreate(@NonNull Activity activity,
        @Nullable Bundle savedInstanceState,
        @Nullable PersistableBundle persistentState) {
    activity.onPostCreate(savedInstanceState, persistentState);
}


protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    if (!isChild()) {
        mTitleReady = true;
        //更新title
        onTitleChanged(getTitle(), getTitleColor());
    }
    mCalled = true;
    notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_START);
}

拓展知识

1.介绍一下Activity的启动流程。

分两种情况,进程未存在,进程已存在。
没存在的话会先跟Zygote建立通信,由Zygote Fork出来子进程 并进入ActivityThread,然后告诉AMS``attachApplication,AMS再告诉客户端 创建Application、loadedApk、Instrumentation 通过Instrumentation的callApplicationOncreate执行Application的Oncreate 生命周期。 然后进行进程存在的流程。
有进程的话直接从这里开始:接着AMS会调用realStartActivity 创建ClientTransaction,设置callback为LaunchActivityItem 添加stateRequest为ResumeActivityItem,分别执行OnCreate,onStart,OnResume,在OnResume中会调用WM和WMS通信绘制UI,再给Looper发送一个Idler和AMS(IPC)通信,让AMS设置Activity的状态信息。

2.ActivityManagerService在创建应用的时候为什么使用socket 而不是用Binder呢?

3.学习activity可以应用场景比如插件化的核心原理?

插件化hook startActivity的函数 将我们的intent修改成我们清单文件中注册过的壳的intent ,start的时候讲我们intent替换,对ams进行欺骗,ams创建我们一系列进程信息操作后,ActivityThread 在handler中 中替换activity

总结

AMS的启动流程图
在这里插入图片描述
Activity的启动流程
在这里插入图片描述

Launcer AMS zygote ActivityThread的交互图
在这里插入图片描述

从Launcher的点击一直到Activity的OnResume的执行。我们来简单的文字总结下流程:
1.在Launcher的ItemClickHandler,最终会调用到Activity的startActivity函数,它会调用到Instrumentation的execStartActivity函数。
2.通过Instrumentation的execStartActivity进行了两次IPC通信,获取到ATMS调用startActivity,它会根据intent来查找activity信息,并且暂停当前Activity,调用到ActivityStackSupervisor的startSpecificActivityLocked判断进程是否存在(wpc.thread),如果进程存在调用realStartActivityLocked来开启Activity,否则调用startProcess开启进程。
3.我们第一次进来进程是不存在的,所以我们会进入开启进程的流程,调用
ProcessList的startProcessLocked设置entryPoint为ActivityThread,通过ZygoteProcess来设置参数,ZygoteConnect发送数据给Zygote,当ZygoteServer接收到数据之后开启ActivityThread的main会创建ActivityThread 调用attach(注意此时我们已经在子进程了),然后IPC告诉AMS 开始attachApplication服务端会把进程存入mPidsSelfLocked进行管理,然后通过thread.bindApplication(IPC)告诉应用端,应用进程就可以创建Application loadedApk Context调用Application的OnCreate。 创建完进程就4次IPC通信了(start的时候两次,创建进程之后告诉AMS 继续AMS的流程 一次,thread.bindApplication 一次)。
4.客户端创建完Application之后在ATMS中会调用attachApplication 接着会调用realStartActivityLocked创建ClientTransaction,设置callback为LaunchActivityItem 添加stateRequest为ResumeActivityItem,调用scheduleTransaction(IPC)调用到ActivityThread的scheduleTransaction函数,调用executeCallBack 也就是执行LaunchActivityItem的execute 它会调用到ActivityThread的handleLaunchActivity,会创建ActivityContext ,通过Instrumentation 反射创建Activity 调用activity的attach 绑定window 再调用callActivityOnCreate 执行Activity的OnCreate。在Activity的OnCreate中分发监听给ActivityLifecycleCallbacks。最后设置当前状态为ON_CREATE。
5.OnCreate之后就会执行executeLifecycleState,之前传递的是ResumeActivityItem,接着调用cycleToPath,之前设置了是ON_CREATE,所以现在里面会存储2 也就是需要执行OnStart,调用performLifecycleSequence 调用ActivityThread.handleStartActivity 分发ActivityLifecycleCallbacks,分发Fragments 调用Instrumentation的callActivityOnStart 设置state为ON_START
6.调用ResumeActivityItem的execute,调用到ActivityThread.handleResumeActivity,调用performResume 分发resume事件给ActivityLifecycleCallbacks,分发Fragments,执行onPostResume 分发onPostResume监听 调用Instrumentation的callActivityOnresume 会调用到Activity的onResume。 最后会再调用r.activity.makeVisible通过WindowManager 添加当前view和WMS(IPC)通信,再给Looper发送一个Idler和AMS(IPC)通信,让AMS设置Activity的状态信息。

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/459049.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Handbook of MusicPsychology 音乐心理学手册 ( 多纳德·霍杰斯 Donald.A.Hodges) 笔记

由两个以上的音组成的结合音&#xff0c;除了该声波的波形&#xff0c;人耳会另外脑补出不存在的波形 频率相距较远的一些音与频率相距较近的一些音&#xff0c;前者累加的响度比后者要大 除了泛音部分&#xff0c;音的起声部分也是音色辨别的关键 音高、响度、音色、时值&a…

托福高频真词List07 // 附托福TPO阅读真题

目录 ​ 4月24日单词 生词 熟词 4月25日真题 4月24日单词 生词 &#x1f361;live in strictly aquatic habitat / əˈkwɑːtɪk / &#x1f361;only live in aquatic environment 只生活在水生环境中 readilyquickly readilyeasily adv 迅速地 adv 轻易地 wide…

聚观早报|中国将是ChatGPT主要对手;​iPhone 15将使用USB-C接口

今日要闻&#xff1a;中国将是ChatGPT主要对手&#xff1b;iPhone 15将使用USB-C接口&#xff1b;31名ChatGPT训练派遣工遭解雇&#xff1b;大疆Mavic 3 Pro无人机高清图曝光&#xff1b;中国红牛回应被禁止生产销售 中国将是ChatGPT主要对手 微软总裁布拉德史密斯接受采访时表…

前端开发之vue动态路由实现方案

前端开发之vue动态路由实现方案 前言2. 实现1、登录页面创建登录函数和watch监听路由2、调用的login方法&#xff08;1&#xff09;登录方法&#xff08;2&#xff09;存储token 3、router.push的时候调用路由守卫&#xff08;1&#xff09;创建路由守卫&#xff0c;建议路由守…

MySQL Community Server 8.0.33安装教程【笔记】

仅安装MySQL Community Server 下载网址&#xff1a;https://dev.mysql.com/downloads/installer/ 1、下载对应版本&#xff1b; 2、下载后&#xff0c;双击安装&#xff0c;弹出界面选择【Custom】&#xff1b; 3、弹出界面选择【MySQL Server 8.0.33 - X64】; 3、弹出界面…

【C++ Metaprogramming】0. 在C++中实现类似C#的泛型类

两年前&#xff0c;笔者因为项目原因刚开始接触C&#xff0c;当时就在想&#xff0c;如果C有类似C#中的泛型限定就好了&#xff0c;能让代码简单许多。我也一度认为&#xff1a; 虽然C有模板类&#xff0c;但是却没办法实现C#中泛型特有的 where 关键词&#xff1a; public c…

Android 13 wificond讲解

wificond介绍 看如下图,可以知道wificond 进程,该进程位于 system/connectivity/wificond 中。wificond 进程通过标准的 nl80211 命令与 Wi-Fi 驱动程序进行通信。 查看手机也能看到wificond 进程 wificond启动 1. 开机的时候通过调用wificond.rc文件启动wificond system…

docker 部署LNMP

准备工作。 #首先获取nginx配置文件 [rootlocalhost ~]# docker pull nginx:1.23.3 [rootlocalhost ~]# docker run --name nginx --restartalways -d -p 80:80 nginx:1.23.3 [rootlocalhost ~]# mkdir -p /usr/local/nginx/{conf,log,html,conf.d} #复制配置文件 [rootlocalh…

易观千帆 | 2023年3月证券APP月活跃用户规模盘点

易观&#xff1a;2023年3月证券服务应用活跃人数14131.58万人&#xff0c;相较上月&#xff0c;环比增长0.61%&#xff0c;同比增长0.60%&#xff1b;2023年3月自营类证券服务应用Top10 活跃人数6221.44万人&#xff0c;环比增长0.08%&#xff1b;2023年3月第三方证券服务应用T…

使用Spring的五大类注解读取和存储Bean

目录 1.存储Bean对象的注解 1.1 五大类注解 1.2 方法注解 1.3添加注解的依赖 2.注解的使用 2.1 controller注解 2. 2Service注解 2.3.Resopsitory注解 2.4Component注解 2.5Configuration注解 2.6 注解之间的关系 3.方法注解 3.1 方法注解要配合类注解来使用。 3.2…

【Python】ddddoc进行OCR识别和目标检测 ——识别验证码和滑块(安装部署+测试代码注释详细)

目录 安装部署gitee已经上传完整项目requiremen.txt插件作者更新地址 项目结构第一部分 OCR识别部分第二部分 目标检测部分总结 欢迎关注 『Python』 系列&#xff0c;持续更新中 欢迎关注 『Python』 系列&#xff0c;持续更新中 安装部署 gitee已经上传完整项目 requiremen.…

图片对象列表查询与展示(vue+springboot+elementUI)

本文描述场景为 展示&#xff1a;后端从数据库中查询图片对象列表&#xff0c;返回前端展示 多图片展示 先看一下后端表实体 import com.zpmc.common.domain.BaseEntity; import io.swagger.annotations.ApiModel; import lombok.*;import javax.persistence.*; import java.…

8086汇编之乘法指令MUL

2023年4月22日&#xff0c;周六晚上。 今天写汇编作业的时候&#xff0c;碰到了MUL指令&#xff0c;于是把学习到的MUL指令知识记录下来&#xff0c;也可以通过写这篇博客彻底理清MUL指令。 当被乘数和乘数都是8位时&#xff1a; 怎么判断被乘数和乘数是不是8位的&#xff1f…

操作系统之认识进程

目录 什么是进程 进程的状态和转换 进程控制 进程通信 什么是进程 在电脑的任务管理器中&#xff0c;能看到电脑当前运行着的所有进程 那到底什么是进程呢&#xff1f;和我们所看所写的那些程序有什么区别&#xff1f; 操作系统是如何区分这些进程的呢&#xff1f; 那就需要…

银河麒麟(桌面版和服务器版)之远程桌面安装

一、前言 在信创方案中经常介绍支持麒麟系统&#xff0c;实际上麒麟分为银河麒麟和中标麒麟&#xff0c;银河麒麟又分为服务器版和桌面版&#xff0c;服务器器版一般用于应用系统部署&#xff0c;桌面版一般用于日常办公。银河麒麟操作系统作为国产操作系统&#xff0c;是目前国…

java定时任务schedule

在 Java中&#xff0c;可以使用定时任务&#xff08;schedule&#xff09;来实现定时任务。这种定时任务能够根据用户的需求进行时间的控制&#xff0c;让用户可以自由设定每一个任务的开始时间和结束时间。 下面来介绍如何使用 java中的定时任务来实现定时任务。 首先需要在配…

# 将pg日志导入pg数据库的几种方法

将pg日志导入pg数据库的几种方法 文章目录 将pg日志导入pg数据库的几种方法1 方法1&#xff1a;官方方法&#xff08;fiel_fdw&#xff09;1.1 创建file_fdw数据源&#xff08;在此之前需要安装pg的file_fdw扩展&#xff09;1.2 创建外部表并导入数据 2 方法2&#xff1a;用csv…

会议论文与期刊论文的写作差异

AI领域的会议论文和期刊论文在撰写方法上存在一定的差异&#xff0c;读者需要理解这些差异&#xff0c;才能做到有的放矢&#xff0c;提高论文的命中率。如果按照会议论文的风格来写期刊论文&#xff0c;或者按照期刊论文的风格来写会议论文&#xff0c;论文命中的概率将大大降…

服务(第十三篇)lvs(负载均衡器)+nginx(反向代理)+tomcat(后端服务器)+nfs共享

准备6台机器&#xff1a; 192.168.169.10 lvs负载均衡器 192.168.169.20、192.168.169.30 nginx反向代理 192.168.169.40&#xff08;tomcat多实例&#xff09;192.168.169.50&#xff08;tomcat&#xff09; 19.168.169.60&#xff08;nfs共享&#xff09; 实验没啥好说的…

新建项目提交到git指定仓库

新建的项目如何上传到git远程仓库&#xff1a; 1&#xff1a;首先进入需要上传的文件夹&#xff0c;鼠标右键点击Git Bash Here 2&#xff1a;输入git init&#xff0c;初始化git相关配置文件 git init3&#xff1a;输入git remote add origin 你的远程仓库地址&#xff0c;…