Android系统服务 AMS 启动流程

110 篇文章 12 订阅
5 篇文章 0 订阅

背景

SystemServer 启动的时候,从Zygote进程fork()SystemServer进程,经过初始化后,会通过反射调用 SystemServer.javamian()方法,其中会启动一系列系统服务。 AMS 就是其中的一个。

一、缘起 SystemServer 进程

SystemServermain():

/**
 * The main entry point from zygote.
 */
public static void main(String[] args) {
    new SystemServer().run();
}

run()方法:

private void run() {
...


// 1 把当前线程作为主线程,绑定looper
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
        SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

// 加载android_servers.so库 
System.loadLibrary("android_servers");

// 初始化系统上下文
createSystemContext();
...
// 创建系统服务的管理者
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
        mRuntimeStartElapsedTime, mRuntimeStartUptime);
        // 加载到本地服务 
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.start();
...

// Start services.
//启动服务 
try {
    t.traceBegin("StartServices");
    startBootstrapServices(t);
    startCoreServices(t);
    startOtherServices(t);
}
...

// 初始化VM的严格模式
StrictMode.initVmDefaults(null);

// Loop forever.
Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");

}

  1. 绑定主线程 looper
  2. 加载 android_servers.so
  3. 创建系统上下文 systemContext
  4. 创建 SystemServerManager
  5. 启动一系列服务
  6. 开启loop循环

1.1 createSystemContext()

private void createSystemContext() {
    
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}


ActivityThread.systemMain()

public static ActivityThread systemMain() {
    // The system process on low-memory devices do not get to use hardware
    // accelerated drawing, since this can add too much overhead to the
    // process.
 
    ActivityThread thread = new ActivityThread();
    // 这里
    thread.attach(true, 0);
    return thread;
}


重点看 attach() 方法 :

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
if (!system) {
    ...
} else {
    // Don't set application object here -- if the system crashes,
    // we can't display an alert, we just want to die die die.
    android.ddm.DdmHandleAppName.setAppName("system_process",
            UserHandle.myUserId());
    try {
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
        ContextImpl context = ContextImpl.createAppContext(
                this, getSystemContext().mPackageInfo);
                //  mPackageInfo 为 LoadApk类型 ,注意第二个参数是null!
        mInitialApplication = context.mPackageInfo.makeApplication(true, null);
        mInitialApplication.onCreate();
    } catch (Exception e) {
        throw new RuntimeException(
                "Unable to instantiate Application():" + e.toString(), e);
    }
}


  1. 创建 Instrumentation 对象,引导类
  2. contextIpml.createSystemContext()创建系统上下文 systemContext。
  3. 根据 mPackageInfo 创建 appContext 对象
  4. 创建 application 对象,表示这个进程的入口
  5. 回调 application 的 onCreate()

1.1.1 getSystemContext()

public ContextImpl getSystemContext() {
    synchronized (this) {
        if (mSystemContext == null) {
            mSystemContext = ContextImpl.createSystemContext(this);
        }
        return mSystemContext;
    }
}

mSystemContextSystemServer 进程是单例对象。

@UnsupportedAppUsage
static ContextImpl createSystemContext(ActivityThread mainThread) {
    LoadedApk packageInfo = new LoadedApk(mainThread);
    ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
            null, null);
    context.setResources(packageInfo.getResources());
    context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
            context.mResourcesManager.getDisplayMetrics());
    return context;
}

  1. new LoadedApk 对象,传入的 systemServer 的 ActivityThread 对象,得到packageInfo,包含系统apk包的所有信息。
  2. new ContextImpl 对象,把 packageInfo 传入,得到 systemContext
  3. 设置资源、更新配置

1.1.2 ContextImpl.createAppContext()

static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo, // 是mSystemContext中 packageInfo: loadApk
        String opPackageName) {
    if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
    ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
            null, opPackageName);
    context.setResources(packageInfo.getResources());
    return context;
}

  1. 根据之前创建的 loadedApk 类型的 packageInfo,创建一个新的 ContextImpl 对象。
  2. 设置资源

到这里,systemServer 进程得到了两个 ContextImpl 对象。

  • 一个是 systemContext systemServer自己使用
  • 一个是 appContext

1.1.3 makeApplication()

public Application makeApplication(boolean forceDefaultAppClass,
        Instrumentation instrumentation) {
        // 只创建一次 
    if (mApplication != null) {
        return mApplication;
    }

    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");

    Application app = null;

    String appClass = mApplicationInfo.className;
    // appclass如果为空,则赋值为 android.app.Application
    if (forceDefaultAppClass || (appClass == null)) {
        appClass = "android.app.Application";
    }

    try {
        // 获得classloader
        java.lang.ClassLoader cl = getClassLoader();
        if (!mPackageName.equals("android")) {
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                    "initializeJavaContextClassLoader");
            initializeJavaContextClassLoader();
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        }
        
        // 再次创建一个contextImpl 对象,
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        // 内部通过反射,创建 application 对象
        app = mActivityThread.mInstrumentation.newApplication(
                cl, appClass, appContext);
                // 
        appContext.setOuterContext(app);
    } catch (Exception e) {
        if (!mActivityThread.mInstrumentation.onException(app, e)) {
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            throw new RuntimeException(
                "Unable to instantiate application " + appClass
                + ": " + e.toString(), e);
        }
    }
    mActivityThread.mAllApplications.add(app);
    mApplication = app;
 // 这里不会被调用,因为传入的是null
    if (instrumentation != null) {
        try {
           
            instrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
            if (!instrumentation.onException(app, e)) {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                throw new RuntimeException(
                    "Unable to create application " + app.getClass().getName()
                    + ": " + e.toString(), e);
            }
        }
    }

    // Rewrite the R 'constants' for all library apks.
    SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers();
    final int N = packageIdentifiers.size();
    for (int i = 0; i < N; i++) {
        final int id = packageIdentifiers.keyAt(i);
        if (id == 0x01 || id == 0x7f) {
            continue;
        }

        rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
    }

    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

    return app;
}

  1. 内部通过反射创建出 application 对象
  2. 调用 setOuterContext()

继续看 mInstrumentationnewApplication() 方法:

1.1.4 newApplication()

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

1.1.5 instantiateApplication()

public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
        @NonNull String className)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        // classloader 加载类对象,反射创建实例对象
    return (Application) cl.loadClass(className).newInstance();
}

classloader 加载类对象,反射创建实例对象 Application

1.1.6 attach()

Application类中:

@UnsupportedAppUsage
/* package */ final void attach(Context context) {
    attachBaseContext(context);
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

protected void attachBaseContext(Context base) {
    if (mBase != null) {
        throw new IllegalStateException("Base context already set");
    }
    mBase = base;
}

至此,systemServer 进程有了三个 contextImpl 对象:

  1. systemContext
  2. appContext
  3. Application 中的mBase contextImpl对象

Application 是继承 contextWraaper 的。contextWraper 又是继承 context 的,因此,Application 想要能够调用 contextImpl 的方法,则必须要要通过 attachBaseContext() 外部设置一个,真正做事的是 contextImpl

1.1.7 callApplicationOnCreate

public void callApplicationOnCreate(Application app) {
    app.onCreate();
}

这里会调用 applicationonCreate 方法。

二、 创建 SystemServerManager

在 systemServer的 run 方法中:

// Create the system service manager.
//构造对象, 传入 systemContext
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
        mRuntimeStartElapsedTime, mRuntimeStartUptime);
        // 注册到本地服务
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

构造对象, 传入 systemContext

LocalServices 功能类似于 SM,但是存入的不是Binder对象。全局存储的对象,更偏向于给本进程使用。

三、startBootstrapServices()

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
...
   // 1 启动 Installer service 用来安装apk
Installer installer = mSystemServiceManager.startService(Installer.class);
...

// Activity manager runs the show. Activity的管理类,开始初始化
// TODO: Might need to move after migration to WM.
//  2 启动一个 ActivityTaskManagerService 
ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
//3, 启动 AMS 
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置installer 
mActivityManagerService.setInstaller(installer);
...

// 4 注册服务 
 mActivityManagerService.setSystemProcess();

3.1 Installer 服务

// 继承了 SystemService
public class Installer extends SystemService

继承了 SystemService。

1 启动 Installer service
Installer installer = mSystemServiceManager.startService(Installer.class);

因为 Installer 是直接继承 systemService 的,因此内部通过反射直接构造对象,注册到内部 mServices 列表中。接着回调 onStart() 方法。

 @Override
    public void onStart() {
        if (mIsolated) {
            mInstalld = null;
        } else {
            // 开始从SM中获取已注册的服务
            connect();
        }
    }

    private void connect() {
        IBinder binder = ServiceManager.getService("installd");
        if (binder != null) {
            try {
                // 如果binder服务已存在,则注册死亡通知,再次连接
                binder.linkToDeath(new DeathRecipient() {
                    @Override
                    public void binderDied() {
                        Slog.w(TAG, "installd died; reconnecting");
                        connect();
                    }
                }, 0);
            } catch (RemoteException e) {
                binder = null;
            }
        }

        if (binder != null) {
            //mInstalld 转成本地代理服务对象
            mInstalld = IInstalld.Stub.asInterface(binder);
            try {
                // 
                invalidateMounts();
            } catch (InstallerException ignored) {
            }
        } else {
            Slog.w(TAG, "installd not found; trying again");
            BackgroundThread.getHandler().postDelayed(() -> {
                connect();
            }, DateUtils.SECOND_IN_MILLIS);// 如果还未注册,则每隔1s 在检测一次
        }
    }

总结:

从 IInstalled 接口 可以看出,提供了 createAppData、clearAppData、getAppSize、dexopt、destroyUserData等等功能。 在启动其他服务之前我们需要 Installed 服务去创建关键性的目录,如 /data/user

interface IInstalld {
21      void createUserData(@nullable @utf8InCpp String uuid, int userId, int userSerial, int flags);
22      void destroyUserData(@nullable @utf8InCpp String uuid, int userId, int flags);
23  
24      long createAppData(@nullable @utf8InCpp String uuid, in @utf8InCpp String packageName,
25              int userId, int flags, int appId, in @utf8InCpp String seInfo, int targetSdkVersion);
26      void restoreconAppData(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
27              int userId, int flags, int appId, @utf8InCpp String seInfo);
28      void migrateAppData(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
29              int userId, int flags);
30      void clearAppData(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
31              int userId, int flags, long ceDataInode);
32      void destroyAppData(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
33              int userId, int flags, long ceDataInode);
34  
35      void fixupAppData(@nullable @utf8InCpp String uuid, int flags);
36  
37      long[] getAppSize(@nullable @utf8InCpp String uuid, in @utf8InCpp String[] packageNames,
38              int userId, int flags, int appId, in long[] ceDataInodes,
39              in @utf8InCpp String[] codePaths);
40      long[] getUserSize(@nullable @utf8InCpp String uuid, int userId, int flags, in int[] appIds);
41      long[] getExternalSize(@nullable @utf8InCpp String uuid, int userId, int flags, in int[] appIds);
42  
43      void setAppQuota(@nullable @utf8InCpp String uuid, int userId, int appId, long cacheQuota);
44  
45      void moveCompleteApp(@nullable @utf8InCpp String fromUuid, @nullable @utf8InCpp String toUuid,
46              @utf8InCpp String packageName, @utf8InCpp String dataAppName, int appId,
47              @utf8InCpp String seInfo, int targetSdkVersion);
48  
49      void dexopt(@utf8InCpp String apkPath, int uid, @nullable @utf8InCpp String packageName,
50              @utf8InCpp String instructionSet, int dexoptNeeded,
51              @nullable @utf8InCpp String outputPath, int dexFlags,
52              @utf8InCpp String compilerFilter, @nullable @utf8InCpp String uuid,
53              @nullable @utf8InCpp String sharedLibraries,
54              @nullable @utf8InCpp String seInfo, boolean downgrade, int targetSdkVersion,
55              @nullable @utf8InCpp String profileName,
56              @nullable @utf8InCpp String dexMetadataPath,
57              @nullable @utf8InCpp String compilationReason);
58      boolean compileLayouts(@utf8InCpp String apkPath, @utf8InCpp String packageName,
59              @utf8InCpp String outDexFile, int uid);
60  
61      void rmdex(@utf8InCpp String codePath, @utf8InCpp String instructionSet);
62  
63      boolean mergeProfiles(int uid, @utf8InCpp String packageName, @utf8InCpp String profileName);
64      boolean dumpProfiles(int uid, @utf8InCpp String packageName, @utf8InCpp String  profileName,
65              @utf8InCpp String codePath);
66      boolean copySystemProfile(@utf8InCpp String systemProfile, int uid,
67              @utf8InCpp String packageName, @utf8InCpp String profileName);
68      void clearAppProfiles(@utf8InCpp String packageName, @utf8InCpp String profileName);
69      void destroyAppProfiles(@utf8InCpp String packageName);
70  
71      boolean createProfileSnapshot(int appId, @utf8InCpp String packageName,
72              @utf8InCpp String profileName, @utf8InCpp String classpath);
73      void destroyProfileSnapshot(@utf8InCpp String packageName, @utf8InCpp String profileName);
74  
75      void idmap(@utf8InCpp String targetApkPath, @utf8InCpp String overlayApkPath, int uid);
76      void removeIdmap(@utf8InCpp String overlayApkPath);
77      void rmPackageDir(@utf8InCpp String packageDir);
78      void markBootComplete(@utf8InCpp String instructionSet);
79      void freeCache(@nullable @utf8InCpp String uuid, long targetFreeBytes,
80              long cacheReservedBytes, int flags);
81      void linkNativeLibraryDirectory(@nullable @utf8InCpp String uuid,
82              @utf8InCpp String packageName, @utf8InCpp String nativeLibPath32, int userId);
83      void createOatDir(@utf8InCpp String oatDir, @utf8InCpp String instructionSet);
84      void linkFile(@utf8InCpp String relativePath, @utf8InCpp String fromBase,
85              @utf8InCpp String toBase);
86      void moveAb(@utf8InCpp String apkPath, @utf8InCpp String instructionSet,
87              @utf8InCpp String outputPath);
88      void deleteOdex(@utf8InCpp String apkPath, @utf8InCpp String instructionSet,
89              @nullable @utf8InCpp String outputPath);
90      void installApkVerity(@utf8InCpp String filePath, in FileDescriptor verityInput,
91              int contentSize);
92      void assertFsverityRootHashMatches(@utf8InCpp String filePath, in byte[] expectedHash);
93  
94      boolean reconcileSecondaryDexFile(@utf8InCpp String dexPath, @utf8InCpp String pkgName,
95          int uid, in @utf8InCpp String[] isas, @nullable @utf8InCpp String volume_uuid,
96          int storage_flag);
97  
98      byte[] hashSecondaryDexFile(@utf8InCpp String dexPath, @utf8InCpp String pkgName,
99          int uid, @nullable @utf8InCpp String volumeUuid, int storageFlag);
100  
101      void invalidateMounts();
102      boolean isQuotaSupported(@nullable @utf8InCpp String uuid);
103  
104      boolean prepareAppProfile(@utf8InCpp String packageName,
105          int userId, int appId, @utf8InCpp String profileName, @utf8InCpp String codePath,
106          @nullable @utf8InCpp String dexMetadata);
107  
108      long snapshotAppData(@nullable @utf8InCpp String uuid, in @utf8InCpp String packageName,
109              int userId, int snapshotId, int storageFlags);
110      void restoreAppDataSnapshot(@nullable @utf8InCpp String uuid, in @utf8InCpp String packageName,
111              int appId, @utf8InCpp String seInfo, int user, int snapshotId, int storageflags);
112      void destroyAppDataSnapshot(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
113              int userId, long ceSnapshotInode, int snapshotId, int storageFlags);
114  
115      void migrateLegacyObbData();
116  
117      const int FLAG_STORAGE_DE = 0x1;
118      const int FLAG_STORAGE_CE = 0x2;
119      const int FLAG_STORAGE_EXTERNAL = 0x4;
120  
121      const int FLAG_CLEAR_CACHE_ONLY = 0x10;
122      const int FLAG_CLEAR_CODE_CACHE_ONLY = 0x20;
123  
124      const int FLAG_FREE_CACHE_V2 = 0x100;
125      const int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 0x200;
126      const int FLAG_FREE_CACHE_NOOP = 0x400;
127  
128      const int FLAG_USE_QUOTA = 0x1000;
129      const int FLAG_FORCE = 0x2000;
130  }
131  

3.2 ActivityTaskManagerService

Android 10 把 activities管理、启动相关的逻辑拆解到了 atm 中。

ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();

内部通过静态内部类 LifeCycle(继承了systemServer) 来管理 atm的生命周期。

3.2.1 atm 构造方法

  public ActivityTaskManagerService(Context context) {
        mContext = context;
        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread(); //获取当前进程的ActivityThread对象
        mUiContext = mSystemThread.getSystemUiContext(); // systemUiContext,包含资源
        
        mLifecycleManager = new ClientLifecycleManager();// 重点:生命周期管理类。activity 就是在这里被管理的
        
        mInternal = new LocalService(); //是atm的内部类,继承ActivityTaskManagerInternal类,类似于本地服务。
        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
    }

  1. 创建了 UIContext 对象 systemServer 进程有四个contextImpl
  2. 创建 ClientLifecycleManager 对象,管理activities生命周期
  3. 创建 mInternal localService 对象,后续的启动 homeActivity就调用了 mInternal的方法。

3.2.2 atm 的 onStart()

Lifecycle 类:

 @Override
        public void onStart() {
            // 往SM中注册 服务
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            // 往本地注册 服务
            mService.start();
        }

 protected final void publishBinderService(String name, IBinder service,
235              boolean allowIsolated, int dumpPriority) {
236          ServiceManager.addService(name, service, allowIsolated, dumpPriority);
237      }
238  

SM 中注册 binder 服务。

 private void start() {
        //class类型, mInternal: localService。
        LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
    }

LocalServices: 类似于SM的功能。不过这里注册的不是Binder对象,并且只能在同一个进程中使用。

3.2.3 atm 的 initialize()

后续 AMS 的构造方法中会调用:

 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
            Looper looper) {
            // looper : DisplayThread的loop
        mH = new H(looper);
        // 创建uihandle ,会创建 UiThread 线程,绑定loop
        mUiHandler = new UiHandler();
        mIntentFirewall = intentFirewall;
        final File systemDir = SystemServiceManager.ensureSystemDir();
        mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
        mCompatModePackages = new CompatModePackages(this, systemDir, mH);
        mPendingIntentController = intentController;

        mTempConfig.setToDefaults();
        mTempConfig.setLocales(LocaleList.getDefault());
        mConfigurationSeq = mTempConfig.seq = 1;
        // 1 创建 ActivityStackSupervisor 对象 ,Activity栈的超级管理
        mStackSupervisor = createStackSupervisor();
        //暂时过渡的类,目的是与RootWindowContainer.java 关联起来
        mRootActivityContainer = new RootActivityContainer(this);
        mRootActivityContainer.onConfigurationChanged(mTempConfig);

        mTaskChangeNotificationController =
                new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
        mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
        mActivityStartController = new ActivityStartController(this);
        mRecentTasks = createRecentTasks();
        //2 设置最近的任务栈 
        mStackSupervisor.setRecentTasks(mRecentTasks);
        mVrController = new VrController(mGlobalLock);
        mKeyguardController = mStackSupervisor.getKeyguardController();
    }

  1. 创建了 UIThread 线程
  2. 创建了 ActivityStackSupervisor : Activity栈的管理类

ActivityStackSupervisor:

  protected ActivityStackSupervisor createStackSupervisor() {
        final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
        supervisor.initialize();
        return supervisor;
    }

前期准备工作基本完成,现在可以真正启动 AMS 了。

四、创建 AMS


mActivityManagerService = ActivityManagerService.Lifecycle.startService( 
mSystemServiceManager, atm); 

mActivityManagerService.setSystemServiceManager(mSystemServiceManager); //设置

installer mActivityManagerService.setInstaller(installer); ... // 4 注册服务 

mActivityManagerService.setSystemProcess();


内部会通过 LifeCycle 静态内部类来完成生命周期管理。

4.1 AMS.LifeCycle

public static final class Lifecycle extends SystemService {
    private final ActivityTaskManagerService mService;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityTaskManagerService(context);
    }

    @Override
    public void onStart() {
        publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
        mService.start();
    }

    @Override
    public void onUnlockUser(int userId) {
        synchronized (mService.getGlobalLock()) {
            mService.mStackSupervisor.onUserUnlocked(userId);
        }
    }

    @Override
    public void onCleanupUser(int userId) {
        synchronized (mService.getGlobalLock()) {
            mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
        }
    }

    public ActivityTaskManagerService getService() {
        return mService;
    }
}

  • 通过反射构造 LifeCycle 对象。构造方法中再创建 AMS 对象。
  • 回调 onStart()方法

4.2 AMS 构造方法

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector();
    mContext = systemContext;

    mFactoryTest = FactoryTest.getMode();
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
    // 创建一个前台线程 ,作为主线程
    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    //mUiHandler 用来通知activities的生命周期
    mUiHandler = mInjector.getUiHandler(this);
    // 新建一个前台线程 procStart
    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
            THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
    mProcessList.init(this, activeUids);
    mLowMemDetector = new LowMemDetector(this);
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

    // Broadcast policy parameters 
    final BroadcastConstants foreConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_FG_CONSTANTS);
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; //10s

    final BroadcastConstants backConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_BG_CONSTANTS);
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; //60s超时

    final BroadcastConstants offloadConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
    offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; //60s超时
    // by default, no "slow" policy in this queue
    offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

    mEnableOffloadQueue = SystemProperties.getBoolean(
            "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
    //前台广播队列 处理超时时长是 10s
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", foreConstants, false);
              //后台广播队列 处理超时时长是 60s
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", backConstants, true);
              //分流广播队列 处理超时时长是 60s
    mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
            "offload", offloadConstants, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;
    mBroadcastQueues[2] = mOffloadBroadcastQueue;

   
    // 四大组件的 service,管理 ServiceRecord
    mServices = new ActiveServices(this);
    // 四大组件 管理  ContentProviderRecord 对象 
    mProviderMap = new ProviderMap(this);

    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);

    final File systemDir = SystemServiceManager.ensureSystemDir();

    // TODO: Move creation of battery stats service outside of activity manager service.
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
            BackgroundThread.get().getHandler());
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true
            : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mBatteryStatsService.getActiveStatistics().setCallback(this);
    mOomAdjProfiler.batteryPowerChanged(mOnBattery);
    // 系统所有进程统计信息
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);

    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);

    mActivityTaskManager = atm;
    // 调用initialize ,内部创建UIthread、stackSuperVisor等
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    // cpu使用runtime 收集线程
    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); //释放CPU
                            }
                        }
                    } 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);

    // bind background threads to little cores
    // this is expected to fail inside of framework tests because apps can't touch cpusets directly
    // make sure we've already adjusted system_server's internal view of itself first
    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");
    }

}

  • activities 管理基本交给了 atm
  • service、contentProvider、broadcast则在 AMS 内部进行管理。
  • 此外还会检测CPU的使用情况、统计系统中所以进程的占用信息。

4.3 AMS start()

private void start() {
    // 移除所有进程组 
    removeAllProcessGroups();
    // 开启CPU使用 监控线程
    mProcessCpuThread.start();
    // 注册 电池服务到SM 和 localServices
    mBatteryStatsService.publish();
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    // 通知atm ActivityManagerInternal已加 
    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");
    }
}

  1. 开启CPU使用 监控线程

4.4 setSystemProcess()

startOtherServices()方法中会 调用 AMS 的setSystemProcess():

private void startOtherServices() {
     ...
     Set up the Application instance for the system process and get started.
     mActivityManagerService.setSystemProcess();
     ...
 }

为system 进程初始化appclication 对象。

public void setSystemProcess() {
       try {
           // 注册AMS
           ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                   DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
           // 注册 ProcessStats 进程统计服务  IProcessStats
           ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
           // 注册 内存信息服务
           ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                   DUMP_FLAG_PRIORITY_HIGH);
           // 注册 图形相关服务
           ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
           // 数据库服务
           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));
           // 注册 processinfo 进程信息服务 IProcessInfoService
           ServiceManager.addService("processinfo", new ProcessInfoService(this));
           // systemServer进程的 application
           ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                   "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
           mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

           synchronized (this) {
               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);
       }

       // Start watching app ops after we and the package manager are up and running.
       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);
                           }
                       }
                   }
               });
   }

  1. 注册各种Binder服务:ams、meminfo、 gfxinfo
  2. 通过解析framework-res.apk里的AndroidManifest.xml获得ApplicationInfo
  3. 为ActivityThread 安装system appInfo信息。最终把 ApplicationInfo 安装到loadedApk中的mApplicationInfo
  4. 新建systemServer的进程对象 processRecord ,用来维护进程信息
  5. 开始监管 app 的操作

4.4 AMS systemReady()

systemServerstartOtherServices()的最后,会调用 AMS 的 systemReady()。表示Android系统已准备好了。内部主要做了三个阶段的工作:

  1. 杀掉在AMS启动前的非常驻进程
  2. 执行goingcallback
  3. 启动homeActivity

4.4.1 阶段一

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
        traceLog.traceBegin("PhaseActivityManagerReady");
        synchronized(this) {
            //1 如果已经ready,则直接运行goingcallback
            if (mSystemReady) {
                // If we're done calling all the receivers, run the next "boot phase" passed in
                // by the SystemServer
                if (goingCallback != null) {
                    goingCallback.run();
                }
                return;
            }

            mLocalDeviceIdleController
                    = LocalServices.getService(DeviceIdleController.LocalService.class);
             //2 调用一系列服务的 onSystemReady()
            mActivityTaskManager.onSystemReady();
            // Make sure we have the current profile info, since it is needed for security checks.
            mUserController.onSystemReady();
            mAppOpsService.systemReady();
            mSystemReady = true; // 修改ready状态
           
        }

        try {
            sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
                    ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
                    .getSerial();
        } catch (RemoteException e) {}

        ArrayList<ProcessRecord> procsToKill = null; // 准备要杀死的进程列表
        synchronized(mPidsSelfLocked) {
            //3  mPidsSelfLocked 保存了所以运行中的进程
            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
                   // 在AMS启动完成前,且info.flag!=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);
                    Slog.i(TAG, "Removing system update proc: " + proc);
                    mProcessList.removeProcessLocked(proc, true, false, "system update done");
                }
            }

            // Now that we have cleaned up any update processes, we
            // are ready to start launching real processes and know that
            // we won't trample on them any more.
            // 至此,system 进程启动完毕
            mProcessesReady = true; 
        }

        Slog.i(TAG, "System now ready");
        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());

        mAtmInternal.updateTopComponentForFactoryTest();
        mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);

        watchDeviceProvisioning(mContext);

        retrieveSettings();
        mUgmInternal.onSystemReady();

        final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
        if (pmi != null) {
            pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
                    state -> updateForceBackgroundCheck(state.batterySaverEnabled));
            updateForceBackgroundCheck(
                    pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
        } else {
            Slog.wtf(TAG, "PowerManagerInternal not found.");
        }
        //阶段二: 运行 systemServer传递过来的 callback。用来通知外部服务systemReady 工作,并启动服务或者应用进程。
        if (goingCallback != null) goingCallback.run();
   
   //...  阶段三 
   
   
   }

  1. 调用一系列服务的 onSystemReady()
  2. 杀掉 AMS 前启动的非常驻进程 ,设置 mProcessesReady = true;

4.4.2 阶段二

执行 goingCallback.run()

 // We now tell the activity manager it is okay to run third party
// code.  It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(() -> {
    Slog.i(TAG, "Making services ready");
    traceBeginAndSlog("StartActivityManagerReadyPhase");
    // 设置bootphase阶段 为 PHASE_ACTIVITY_MANAGER_READY=550
    // 该阶段后 系统服务可以发送广播了
    mSystemServiceManager.startBootPhase(
            SystemService.PHASE_ACTIVITY_MANAGER_READY);
    traceEnd();
    traceBeginAndSlog("StartObservingNativeCrashes");
    try {
        // 开始监控 native 奔溃 
        mActivityManagerService.startObservingNativeCrashes();
    } catch (Throwable e) {
        reportWtf("observing native crashes", e);
    }
    traceEnd();

    // No dependency on Webview preparation in system server. But this should
    // be completed before allowing 3rd party
    final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
    Future<?> webviewPrep = null;
    // 启动 webview 
    if (!mOnlyCore && mWebViewUpdateService != null) {
        webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
            Slog.i(TAG, WEBVIEW_PREPARATION);
            TimingsTraceLog traceLog = new TimingsTraceLog(
                    SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
            traceLog.traceBegin(WEBVIEW_PREPARATION);
            ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
            mZygotePreload = null;
            mWebViewUpdateService.prepareWebViewInSystemServer();
            traceLog.traceEnd();
        }, WEBVIEW_PREPARATION);
    }

    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
        traceBeginAndSlog("StartCarServiceHelperService");
        mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
        traceEnd();
    }

    traceBeginAndSlog("StartSystemUI");
    try {
       // 开始系统ui界面,通过启动一个服务service 
        startSystemUi(context, windowManagerF);
    } catch (Throwable e) {
        reportWtf("starting System UI", e);
    }
    traceEnd();
    // Enable airplane mode in safe mode. setAirplaneMode() cannot be called
    // earlier as it sends broadcasts to other services.
    // TODO: This may actually be too late if radio firmware already started leaking
    // RF before the respective services start. However, fixing this requires changes
    // to radio firmware and interfaces.
    if (safeMode) {
        traceBeginAndSlog("EnableAirplaneModeInSafeMode");
        try {
            connectivityF.setAirplaneMode(true);
        } catch (Throwable e) {
            reportWtf("enabling Airplane Mode during Safe Mode bootup", e);
        }
        traceEnd();
    }
    traceBeginAndSlog("MakeNetworkManagementServiceReady");
    try {
        if (networkManagementF != null) {
            networkManagementF.systemReady();
        }
    } catch (Throwable e) {
        reportWtf("making Network Managment Service ready", e);
    }
    CountDownLatch networkPolicyInitReadySignal = null;
    if (networkPolicyF != null) {
        networkPolicyInitReadySignal = networkPolicyF
                .networkScoreAndNetworkManagementServiceReady();
    }
    // 一系列的 systemReady() 通知
    traceEnd();
    traceBeginAndSlog("MakeIpSecServiceReady");
    try {
        if (ipSecServiceF != null) {
            ipSecServiceF.systemReady();
        }
    } catch (Throwable e) {
        reportWtf("making IpSec Service ready", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeNetworkStatsServiceReady");
    try {
        if (networkStatsF != null) {
            networkStatsF.systemReady();
        }
    } catch (Throwable e) {
        reportWtf("making Network Stats Service ready", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeConnectivityServiceReady");
    try {
        if (connectivityF != null) {
            connectivityF.systemReady();
        }
    } catch (Throwable e) {
        reportWtf("making Connectivity Service ready", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeNetworkPolicyServiceReady");
    try {
        if (networkPolicyF != null) {
            networkPolicyF.systemReady(networkPolicyInitReadySignal);
        }
    } catch (Throwable e) {
        reportWtf("making Network Policy Service ready", e);
    }
    traceEnd();

    // Wait for all packages to be prepared
    mPackageManagerService.waitForAppDataPrepared();

    // It is now okay to let the various system services start their
    // third party code...
    traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
    // confirm webview completion before starting 3rd party
    if (webviewPrep != null) {
        ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
    }
    // 阶段600 在此阶段后,系统服务可以去启动/绑定第三方的 app了。
    //同时 app 也可以发起binder调用了 
    mSystemServiceManager.startBootPhase(
            SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
    traceEnd();

    traceBeginAndSlog("StartNetworkStack");
    try {
        // Note : the network stack is creating on-demand objects that need to send
        // broadcasts, which means it currently depends on being started after
        // ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady
        // are set to true. Be careful if moving this to a different place in the
        // startup sequence.
        NetworkStackClient.getInstance().start(context);
    } catch (Throwable e) {
        reportWtf("starting Network Stack", e);
    }
    traceEnd();

    traceBeginAndSlog("MakeLocationServiceReady");
    try {
        if (locationF != null) {
            locationF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying Location Service running", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeCountryDetectionServiceReady");
    try {
        if (countryDetectorF != null) {
            countryDetectorF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying CountryDetectorService running", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeNetworkTimeUpdateReady");
    try {
        if (networkTimeUpdaterF != null) {
            networkTimeUpdaterF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying NetworkTimeService running", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeInputManagerServiceReady");
    try {
        // TODO(BT) Pass parameter to input manager
        if (inputManagerF != null) {
            inputManagerF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying InputManagerService running", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeTelephonyRegistryReady");
    try {
        if (telephonyRegistryF != null) {
            telephonyRegistryF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying TelephonyRegistry running", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeMediaRouterServiceReady");
    try {
        if (mediaRouterF != null) {
            mediaRouterF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying MediaRouterService running", e);
    }
    traceEnd();
    traceBeginAndSlog("MakeMmsServiceReady");
    try {
        if (mmsServiceF != null) {
            mmsServiceF.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying MmsService running", e);
    }
    traceEnd();

    traceBeginAndSlog("IncidentDaemonReady");
    try {
        // TODO: Switch from checkService to getService once it's always
        // in the build and should reliably be there.
        final IIncidentManager incident = IIncidentManager.Stub.asInterface(
                ServiceManager.getService(Context.INCIDENT_SERVICE));
        if (incident != null) {
            incident.systemRunning();
        }
    } catch (Throwable e) {
        reportWtf("Notifying incident daemon running", e);
    }
    traceEnd();
}, BOOT_TIMINGS_TRACE_LOG);

  1. 设置bootphase阶段 为 PHASE_ACTIVITY_MANAGER_READY=550。该阶段后 系统服务可以发送广播了
  2. 开始监控 native 奔溃
  3. 启动 webview
  4. 启动系统UI的服务service
  5. 一系列的 systemReady() 通知
  6. 阶段600 在此阶段后,系统服务可以去启动/绑定第三方的 app了。 更重要的是 app 可以发起binder调用了
  7. 一些服务 systemRunning() 回调

4.4.3 阶段三

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
  //...
  
// Check the current user here as a user can be started inside goingCallback.run() from
// other system services.
final int currentUserId = mUserController.getCurrentUserId();
Slog.i(TAG, "Current user:" + currentUserId);
if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
    // User other than system user has started. Make sure that system user is already
    // started before switching user.
    throw new RuntimeException("System user not started while current user is:"
            + currentUserId);
}
traceLog.traceBegin("ActivityManagerStartApps");
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
        Integer.toString(currentUserId), currentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
        Integer.toString(currentUserId), currentUserId);
  //调用所有系统服务的onStartUser接口 
mSystemServiceManager.startUser(currentUserId);

synchronized (this) {
    // Only start up encryption-aware persistent apps; once user is
    // unlocked we'll come back around and start unaware apps
    //启动persistent为1的application所在的进程
    startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);

    // Start up initial activity.
    mBooting = true;
    // Enable home activity for system user, so that the system can always boot. We don't
    // do this when the system user is not setup since the setup wizard should be the one
    // to handle home activity in this case.
    if (UserManager.isSplitSystemUser() &&
            Settings.Secure.getInt(mContext.getContentResolver(),
                 Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
        ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
        try {
            AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
                    UserHandle.USER_SYSTEM);
        } catch (RemoteException e) {
            throw e.rethrowAsRuntimeException();
        }
    }
    
    //启动Home Activity
    mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");

    mAtmInternal.showSystemReadyErrorDialogsIfNeeded();

    final int callingUid = Binder.getCallingUid();
    final int callingPid = Binder.getCallingPid();
    long ident = Binder.clearCallingIdentity();
    try {
        // system发送广播 ACTION_USER_STARTED = "android.intent.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);
    } catch (Throwable t) {
        Slog.wtf(TAG, "Failed sending first user broadcasts", t);
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
    // resumeTopActivity 
    mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
    mUserController.sendUserSwitchBroadcasts(-1, currentUserId);

    BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
            BINDER_PROXY_LOW_WATERMARK);
    BinderInternal.nSetBinderProxyCountEnabled(true);
    BinderInternal.setBinderProxyCountCallback(
            new BinderInternal.BinderProxyLimitListener() {
                @Override
                public void onLimitReached(int uid) {
                    Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
                            + Process.myUid());
                    BinderProxy.dumpProxyDebugInfo();
                    if (uid == Process.SYSTEM_UID) {
                        Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
                    } else {
                        killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
                                "Too many Binders sent to SYSTEM");
                    }
                }
            }, mHandler);

    traceLog.traceEnd(); // ActivityManagerStartApps
    traceLog.traceEnd(); // PhaseActivityManagerReady
}

  1. 调用所有系统服务的onStartUser接口
  2. 启动persistent为1的 application 所在的进程
  3. 启动Home Activity: startHomeOnAllDisplays
  4. 发送广播 ACTION_USER_STARTED = "android.intent.action.USER_STARTED";
  5. 发送广播 ACTION_USER_STARTING
  6. resumeTopActivities()
4.4.3.1 startHomeOnAllDisplays()
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");

mAtmInternalActivityTaskManagerInternal 类型,会调用到它的子类 LocalService

怎么获取 mAtmInternal 呢?

ActivityManagerService.java

mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

什么时候注册呢?

在 atm 的start()方法中:

ActivityTaskManagerService.java

//atm 构造方法中
mInternal = new LocalService();


private void start() {
    LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}

因此,我们直接看 LocalService(是ActivityTaskManagerService的静态内部类) 的 startHomeOnAllDisplays():

@Override
public boolean startHomeOnAllDisplays(int userId, String reason) {
    synchronized (mGlobalLock) {
        return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
    }
}

RootActivityContainer.java

boolean startHomeOnAllDisplays(int userId, String reason) {
    boolean homeStarted = false;
    for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
        final int displayId = mActivityDisplays.get(i).mDisplayId;
        homeStarted |= startHomeOnDisplay(userId, reason, displayId);
    }
    return homeStarted;
}

boolean startHomeOnDisplay(int userId, String reason, int displayId) {
    return startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */,
            false /* fromHomeKey */);
}

boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
        boolean fromHomeKey) {
    // Fallback to top focused display if the displayId is invalid.
    if (displayId == INVALID_DISPLAY) {
        displayId = getTopDisplayFocusedStack().mDisplayId;
    }

    Intent homeIntent = null;
    ActivityInfo aInfo = null;
    if (displayId == DEFAULT_DISPLAY) {
        // category: 为 CATEGORY_HOME
        homeIntent = mService.getHomeIntent();
        //解析得到 ActivityInfo
        aInfo = resolveHomeActivity(userId, homeIntent);
    } else if (shouldPlaceSecondaryHomeOnDisplay(displayId)) {
        Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, displayId);
        aInfo = info.first;
        homeIntent = info.second;
    }
    if (aInfo == null || homeIntent == null) {
        return false;
    }

    if (!canStartHomeOnDisplay(aInfo, displayId, allowInstrumenting)) {
        return false;
    }

    // Updates the home component of the intent.
    homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
    homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
    // Updates the extra information of the intent.
    if (fromHomeKey) {
        homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
    }
    // Update the reason for ANR debugging to verify if the user activity is the one that
    // actually launched.
    final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
            aInfo.applicationInfo.uid) + ":" + displayId;
    mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
            displayId);
    return true;
}

最终,通过 startHomeActivity() 来启动 launch 进程。

五、总结

AMS 主要做了如下工作:

  1. 为 system 创建环境: systemContext
  2. 创建 AMS 对象,注册一系列的服务,如:管理四大组件、内存、CPU使用监控等
  3. 为 system 进程创建 processRecord,加入到AMS的进程管理中
  4. 启动 homeActivity ,拉起launch进程

文末福利

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。
在这里插入图片描述
相对于我们平时看的碎片化内容,这份笔记的知识点更系统化,更容易理解和记忆,是严格按照知识体系编排的。

一、架构师筑基必备技能

1、深入理解Java泛型
2、注解深入浅出
3、并发编程
4、数据传输与序列化
5、Java虚拟机原理
6、高效IO
……

在这里插入图片描述

二、Android百大框架源码解析

1.Retrofit 2.0源码解析
2.Okhttp3源码解析
3.ButterKnife源码解析
4.MPAndroidChart 源码解析
5.Glide源码解析
6.Leakcanary 源码解析
7.Universal-lmage-Loader源码解析
8.EventBus 3.0源码解析
9.zxing源码分析
10.Picasso源码解析
11.LottieAndroid使用详解及源码解析
12.Fresco 源码分析——图片加载流程

在这里插入图片描述

三、Android性能优化实战解析

  • 腾讯Bugly:对字符串匹配算法的一点理解
  • 爱奇艺:安卓APP崩溃捕获方案——xCrash
  • 字节跳动:深入理解Gradle框架之一:Plugin, Extension, buildSrc
  • 百度APP技术:Android H5首屏优化实践
  • 支付宝客户端架构解析:Android 客户端启动速度优化之「垃圾回收」
  • 携程:从智行 Android 项目看组件化架构实践
  • 网易新闻构建优化:如何让你的构建速度“势如闪电”?

在这里插入图片描述

四、高级kotlin强化实战

1、Kotlin入门教程
2、Kotlin 实战避坑指南
3、项目实战《Kotlin Jetpack 实战》

  • 从一个膜拜大神的 Demo 开始

  • Kotlin 写 Gradle 脚本是一种什么体验?

  • Kotlin 编程的三重境界

  • Kotlin 高阶函数

  • Kotlin 泛型

  • Kotlin 扩展

  • Kotlin 委托

  • 协程“不为人知”的调试技巧

  • 图解协程:suspend

在这里插入图片描述

五、Android高级UI开源框架进阶解密

1.SmartRefreshLayout的使用
2.Android之PullToRefresh控件源码解析
3.Android-PullToRefresh下拉刷新库基本用法
4.LoadSir-高效易用的加载反馈页管理框架
5.Android通用LoadingView加载框架详解
6.MPAndroidChart实现LineChart(折线图)
7.hellocharts-android使用指南
8.SmartTable使用指南
9.开源项目android-uitableview介绍
10.ExcelPanel 使用指南
11.Android开源项目SlidingMenu深切解析
12.MaterialDrawer使用指南
在这里插入图片描述

六、NDK模块开发

1、NDK 模块开发
2、JNI 模块
3、Native 开发工具
4、Linux 编程
5、底层图片处理
6、音视频开发
7、机器学习

在这里插入图片描述

七、Flutter技术进阶

1、Flutter跨平台开发概述
2、Windows中Flutter开发环境搭建
3、编写你的第一个Flutter APP
4、Flutter开发环境搭建和调试
5、Dart语法篇之基础语法(一)
6、Dart语法篇之集合的使用与源码解析(二)
7、Dart语法篇之集合操作符函数与源码分析(三)

在这里插入图片描述

八、微信小程序开发

1、小程序概述及入门
2、小程序UI开发
3、API操作
4、购物商场项目实战……

在这里插入图片描述

全套视频资料:

一、面试合集
在这里插入图片描述
二、源码解析合集

在这里插入图片描述
三、开源框架合集

在这里插入图片描述
欢迎大家一键三连支持,若需要文中资料,直接点击文末CSDN官方认证微信卡片免费领取↓↓↓

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android系统启动流程可以简单分为以下几个步骤:\[1\] 1. 前期准备工作:包括系统服务的初始化、创建ActivityThread线程等。 2. 启动AMS:创建ActivityManagerService对象,并注册系统服务。 3. 启动Zygote进程:Zygote是Android系统的孵化器进程,负责创建新的应用进程。 4. 创建应用进程:Zygote根据应用的包名创建新的应用进程,并加载应用的代码和资源。 5. 启动应用:应用进程启动后,会创建Application对象,并执行Application的生命周期方法。 6. 创建Activity:应用启动后,根据启动模式和Intent创建相应的Activity,并进行Activity的生命周期管理。 7. 显示界面:Activity创建完成后,会通过WindowManagerService进行窗口管理,将界面显示到屏幕上。 在AMS加载Application的流程中,主要包括以下几个步骤:\[3\] 1. 前期准备工作:包括创建ActivityManagerService对象、注册系统服务等。 2. 创建Application对象:根据应用的包名和类名,通过反射创建Application对象。 3. 调用Application的生命周期方法:调用Application的attachBaseContext()、onCreate()等生命周期方法,完成应用的初始化工作。 在启动过程中,需要处理的问题包括:\[1\] 1. 冷启动时间过长:可以通过优化应用的启动流程、减少启动时的耗时操作等方式来缩短冷启动时间。 2. 黑白屏问题:可以通过在启动过程中显示一个启动界面,或者使用启动图等方式来解决黑白屏问题。 3. 启动优化:可以通过优化应用的启动流程、减少启动时的资源加载等方式来提升应用的启动速度和执行效率。 WMS(Window Manager Service)对启动优化的意义在于,它负责管理应用的窗口显示,包括界面的布局、绘制等。通过优化WMS的处理流程,可以提升应用的界面显示效果和响应速度,从而提升用户体验。\[2\] #### 引用[.reference_title] - *1* *2* [Android面试题——高级开发面试题一](https://blog.csdn.net/Calvin_zhou/article/details/128123302)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Android系统服务 AMS 启动流程](https://blog.csdn.net/bugyinyin/article/details/126520417)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值