目录

一、出生地:

SystemServer.run()方法:

Systemserver.startBootstarpServices(t)方法:

二、SystemServiceManger

SystemServiceManager.startService的流程

ActivityTaskManagerService.Lifecycle

SystemService.publishBinderService

SystemServiceManager.startService时序图:

三、ActivityManagerService启动流程

ActivityManagerService的启动时序图:

四、ActivityManagerService在启动之后还做了什么

五、AMS和ATMS的接口简介

Activity管理:

Stack管理:

Task管理:

初始化操作

Configuration和Orientation

状态监听

角色图:

问题:


查看android 源码最方便的就是https://cs.android.com/ 只不过需要翻墙。

AMS是android非常复杂的一个类,要想细致的研究它,有些时候不可能面面俱到。我认为有时候就像观赏风景一样,一座山很大,要想一下子都观赏完是不可能的。走走停停,走马观花,然后再重要的景点上驻足,在墙上写上“到此一游”。

我们要学习ActivityManagerService那就先从它是怎么出生的开始吧。

一、出生地:

AMS的出生地在SystemServer的main()方法,可以查看frameworks/base/services/java/com/android/server/SystemServer.java

Code block1:

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

SystemServer.run()方法:

SystemServer.run()方法有200行。把主要的代码粘在下面:

Code block2:

    private void run() {TimingsTraceAndSlog t = new TimingsTraceAndSlog();try {t.traceBegin("InitBeforeStartServices");// Record the process start information in sys props.SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));......// Start services.try {t.traceBegin("StartServices");startBootstrapServices(t);// code snippet 1startCoreServices(t);startOtherServices(t);} catch (Throwable ex) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting system services", ex);throw ex;} finally {t.traceEnd(); // StartServices}......}

Systemserver.startBootstarpServices(t)方法:

Code block3:

    /*** Starts the small tangle of critical services that are needed to get the system off the* ground.  These services have complex mutual dependencies which is why we initialize them all* in one place here.  Unless your service is also entwined in these dependencies, it should be* initialized in one of the other functions.*/private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {t.traceBegin("startBootstrapServices");......// Activity manager runs the show.t.traceBegin("StartActivityManager");// TODO: Might need to move after migration to WM.ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();//code snippet 2mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);//code snippet 3mActivityManagerService.setSystemServiceManager(mSystemServiceManager);mActivityManagerService.setInstaller(installer);......}

到现在为至,出场的角色有:

  • SystemServiceManger
  • ActivityTaskManagerService
  • ActivityTaskManagerService.Lifecycle
  • ActivityManagerService
  • ActivityManagerService.Lifecycle

在code snippet2中SystemServiceManger首先登场,调用了其startService方法,参数为ActivityTaskManagerService.Lifecycle

二、SystemServiceManger

看一下SystemServiceManger的类的主要代码:

Code block4:

/*** Manages creating, starting, and other lifecycle events of* {@link com.android.server.SystemService system services}.** {@hide}*/
public class SystemServiceManager {// Services that should receive lifecycle events.private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();//code snippet 4/*** Publish the service so it is accessible to other services and apps.** @param name the name of the new service* @param service the service object*/protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) {publishBinderService(name, service, false);}/*** Starts a service by class name.** @return The service instance.*/public SystemService startService(String className) {//code snippet 5final Class<SystemService> serviceClass = loadClassFromLoader(className,this.getClass().getClassLoader());return startService(serviceClass);}/*** Creates and starts a system service. The class must be a subclass of* {@link com.android.server.SystemService}.** @param serviceClass A Java class that implements the SystemService interface.* @return The service instance, never null.* @throws RuntimeException if the service fails to start.*/public <T extends SystemService> T startService(Class<T> serviceClass) {try {final String name = serviceClass.getName();Slog.i(TAG, "Starting " + name);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);// Create the service.if (!SystemService.class.isAssignableFrom(serviceClass)) {throw new RuntimeException("Failed to create " + name+ ": service must extend " + SystemService.class.getName());}final T service;try {Constructor<T> constructor = serviceClass.getConstructor(Context.class);//code snippet 6service = constructor.newInstance(mContext);} catch (InstantiationException ex) {throw new RuntimeException("Failed to create service " + name+ ": service could not be instantiated", ex);} catch (IllegalAccessException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (NoSuchMethodException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (InvocationTargetException ex) {throw new RuntimeException("Failed to create service " + name+ ": service constructor threw an exception", ex);}startService(service);//code snippet 7return service;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}}public void startService(@NonNull final SystemService service) {// Register it.mServices.add(service);// Start it.long time = SystemClock.elapsedRealtime();try {service.onStart();//code snippet 8} catch (RuntimeException ex) {throw new RuntimeException("Failed to start service " + service.getClass().getName()+ ": onStart threw an exception", ex);}warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");}
}

从SystemServiceManager的命令就能猜到,它是一个管理类,用于管理SystemService的。从类的注释“Manages creating, starting, and other lifecycle events of system services”就能明白了,它控制system service的生命周期事情。

在code snippet 4中可以看到有一个名叫mServicesArrayList存了管理的所有System service。

SystemServiceManager.startService的流程

现在,我们来说说SystemServiceManager.startService的流程:

  1. 在code block3的code snippet2开始mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class)
  2. 再调到code block4的code snippet5的startService方法
  3. code block4的code snippet6的Constructor<T> constructor = serviceClass.getConstructor(Context.class);和service = constructor.newInstance(mContext); 
    1. 这一步运行了ActivityTaskManagerService.Lifecycle.class的构造,并实例化得到一个名为service的SystemService
  4. 调用startService(service)在code snippet 8高用service.onStart(),即ActivityTaskManagerService.Lifecycle的onStart()

ActivityTaskManagerService.Lifecycle

从上面的流程看,有必要看一下ActivityTaskManagerService.Lifecycle的代码:

Code block5:

/*** System service for managing activities and their containers (task, stacks, displays,... ).** {@hide}*/
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {private void start() {//code snippet 11LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);}public static final class Lifecycle extends SystemService {private final ActivityTaskManagerService mService;public Lifecycle(Context context) {super(context);mService = new ActivityTaskManagerService(context);}@Overridepublic void onStart() {publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);//code snippet 9mService.start();//code snippet 10}public ActivityTaskManagerService getService() {return mService;}}}

上面SystemServiceManager.startService流程最后调到了ActivityTaskManagerService.Lifecycle的onStart()。

ActivityTaskManagerService.Lifecycle的onStart()调到了code snippet 9 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);和code snippet 10的mService.start();

code snippet 10的mService.start()比较要理解,调了外部类ActivityTaskManagerService的start方法。

publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService)的作用是什么呢?

SystemService.publishBinderService

咱们来主要看一下publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService)的作用:

Code block 6:

/*** The base class for services running in the system process. Override and implement* the lifecycle event callback methods as needed.* <p>* The lifecycle of a SystemService:* </p><ul>* <li>The constructor is called and provided with the system {@link Context}* to initialize the system service.* <li>{@link #onStart()} is called to get the service running.  The service should* publish its binder interface at this point using* {@link #publishBinderService(String, IBinder)}.  It may also publish additional* local interfaces that other services within the system server may use to access* privileged internal functions.* <li>Then {@link #onBootPhase(int)} is called as many times as there are boot phases* until {@link #PHASE_BOOT_COMPLETED} is sent, which is the last boot phase. Each phase* is an opportunity to do special work, like acquiring optional service dependencies,* waiting to see if SafeMode is enabled, or registering with a service that gets* started after this one.* </ul><p>* NOTE: All lifecycle methods are called from the system server's main looper thread.* </p>** {@hide}*/
@SystemApi(client = Client.SYSTEM_SERVER)
public abstract class SystemService {/*** Publish the service so it is accessible to other services and apps.** @param name the name of the new service* @param service the service object*/protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) {publishBinderService(name, service, false);}/*** Publish the service so it is accessible to other services and apps.** @param name the name of the new service* @param service the service object* @param allowIsolated set to true to allow isolated sandboxed processes* to access this service* @param dumpPriority supported dump priority levels as a bitmask** @hide*/protected final void publishBinderService(String name, IBinder service,boolean allowIsolated, int dumpPriority) {ServiceManager.addService(name, service, allowIsolated, dumpPriority);}}

从上面的代码可以看出最后把service 添加到了ServiceManager里了。

SystemServiceManager.startService时序图:

三、ActivityManagerService启动流程

从Code block3的code snippet 3的代码mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm); 其中参数atm是上面分析提到的已经启动的ActivityTaskManagerService。

来看一下ActivityManagerService.Lifecycle.startService的代码:

Code block7:

public class ActivityManagerService extends IActivityManager.Stubimplements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {//code snippet 24// Note: This method is invoked on the main thread but may need to attach various// handlers to other threads.  So take care to be explicit about the looper.public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);mInjector = new Injector(systemContext);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 = mInjector.getUiHandler(this);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 */);mPlatformCompat = (PlatformCompat) ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);mProcessList = mInjector.getProcessList(this);mProcessList.init(this, activeUids, mPlatformCompat);mLowMemDetector = new LowMemDetector(this);mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);// Broadcast policy parametersfinal BroadcastConstants foreConstants = new BroadcastConstants(Settings.Global.BROADCAST_FG_CONSTANTS);foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;final BroadcastConstants backConstants = new BroadcastConstants(Settings.Global.BROADCAST_BG_CONSTANTS);backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;final BroadcastConstants offloadConstants = new BroadcastConstants(Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;// by default, no "slow" policy in this queueoffloadConstants.SLOW_TIME = Integer.MAX_VALUE;mEnableOffloadQueue = SystemProperties.getBoolean("persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);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;mServices = new ActiveServices(this);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, mConstants);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;mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,DisplayThread.get().getLooper());mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);mProcessCpuThread = new Thread("CpuTracker") {@Overridepublic 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);// 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 firstupdateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);try {Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),Process.THREAD_GROUP_SYSTEM);Process.setThreadGroupAndCpuset(mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),Process.THREAD_GROUP_SYSTEM);} catch (Exception e) {Slog.w(TAG, "Setting background thread cpuset failed");}mInternal = new LocalService();mPendingStartActivityUids = new PendingStartActivityUids(mContext);}public static final class Lifecycle extends SystemService {private final ActivityManagerService mService;private static ActivityTaskManagerService sAtm;public Lifecycle(Context context) {super(context);mService = new ActivityManagerService(context, sAtm);}public static ActivityManagerService startService(SystemServiceManager ssm, ActivityTaskManagerService atm) {sAtm = atm;return ssm.startService(ActivityManagerService.Lifecycle.class).getService();//code snippet 11}@Overridepublic void onStart() {mService.start();}}

ActivityManagerService.Lifecycle.startService方法传进来两个参数:1个是ssm,即SystemServiceManager;1个是atm,即ActivityTaskManagerService。

看到code snippet11的ssm。startService是不是很熟悉了。它就是上面分析的SystemServiceManager.startService的流程。

那么现在ActivityManagerService的启动流程就清晰了:

  1. 由SystemServiceManager启动,启动过程调用ActivityManagerService.Lifecycle的构造方法并实例化
  2. 在ActivityManagerService.Lifecycle的构造方法里new了ActivityManagerService。这时把一个ActivityTaskManagerService实例传给了ActivityManagerService。构造方法请看上面的Code block7的code snippet24。
  3. 调用ActivityManagerService.Lifecycle的onStart()方法。进而调到了ActivityManagerService的start()方法。

ActivityManagerService start方法:

Code block8:

public class ActivityManagerService extends IActivityManager.Stubimplements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {private void start() {removeAllProcessGroups();mProcessCpuThread.start();mBatteryStatsService.publish();mAppOpsService.publish();Slog.d("AppOps", "AppOpsService published");LocalServices.addService(ActivityManagerInternal.class, mInternal);mActivityTaskManager.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");}}
}

ActivityManagerService的启动时序图:

四、ActivityManagerService在启动之后还做了什么

还是从SystemServer的startBootstrapServices()方法开始看:

Code block9:

    /*** Starts the small tangle of critical services that are needed to get the system off the* ground.  These services have complex mutual dependencies which is why we initialize them all* in one place here.  Unless your service is also entwined in these dependencies, it should be* initialized in one of the other functions.*/private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);mActivityManagerService.setSystemServiceManager(mSystemServiceManager);//code snippet 12mActivityManagerService.setInstaller(installer);//code snippet 13// Power manager needs to be started early because other services need it.// Native daemons may be watching for it to be registered so it must be ready// to handle incoming binder calls immediately (including being able to verify// the permissions for those calls).mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);// Now that the power manager has been started, let the activity manager// initialize power management features.mActivityManagerService.initPowerManagement();//code snippet 14// Set up the Application instance for the system process and get started.mActivityManagerService.setSystemProcess();//code snippet 15if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {// DisplayManager needs the overlay immediately.mActivityManagerService.updateSystemUiContext();//code snippet 16LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();}}

在SystemServer的startBootstrapServices()方法中,在ActivityManagerService启动之后顺序执行了:

  1. code snippet12: mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  2. code snippet13: mActivityManagerService.setInstaller(installer);
  3. code snippet14: mActivityManagerService.initPowerManagement();
  4. code snippet15: mActivityManagerService.setSystemProcess();
  5. code snippet16: if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) mActivityManagerService.updateSystemUiContext();

接着是SystemServer的startCoreServices()方法:

Code block10:

    /*** Starts some essential services that are not tangled up in the bootstrap process.*/private void startCoreServices(@NonNull TimingsTraceAndSlog t) {mSystemServiceManager.startService(UsageStatsService.class);mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));//code snippet 17}

在SystemServer的startCoreServices()方法中,只有一个调用:

  • code snippet17: mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));

然后是SystemServer的startOtherServices()方法:

Code block11:

    /*** Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.*/private void startOtherServices(@NonNull TimingsTraceAndSlog t) {mActivityManagerService.installSystemProviders();//code snippet 18wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);mActivityManagerService.setWindowManager(wm);//code snippet 19if (safeMode) {mActivityManagerService.enterSafeMode();//code snippet 20}// Emit any pending system_server WTFssynchronized (SystemService.class) {if (sPendingWtfs != null) {mActivityManagerService.schedulePendingSystemServerWtfs(sPendingWtfs);//code snippet 21sPendingWtfs = null;}}if (safeMode) {mActivityManagerService.showSafeModeOverlay();//code snippet 22}// 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(() -> {//code snippet 23Slog.i(TAG, "Making services ready");mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);try {mActivityManagerService.startObservingNativeCrashes();} catch (Throwable e) {reportWtf("observing native crashes", e);}// No dependency on Webview preparation in system server. But this should// be completed before allowing 3rd partyfinal String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";Future<?> webviewPrep = null;if (!mOnlyCore && mWebViewUpdateService != null) {webviewPrep = SystemServerInitThreadPool.submit(() -> {Slog.i(TAG, WEBVIEW_PREPARATION);TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");mZygotePreload = null;mWebViewUpdateService.prepareWebViewInSystemServer();}, WEBVIEW_PREPARATION);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);}try {startSystemUi(context, windowManagerF);} catch (Throwable e) {reportWtf("starting System UI", e);}// 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) {t.traceBegin("EnableAirplaneModeInSafeMode");try {connectivityF.setAirplaneMode(true);} catch (Throwable e) {reportWtf("enabling Airplane Mode during Safe Mode bootup", e);}t.traceEnd();}t.traceBegin("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();}t.traceEnd();t.traceBegin("MakeIpSecServiceReady");try {if (ipSecServiceF != null) {ipSecServiceF.systemReady();}} catch (Throwable e) {reportWtf("making IpSec Service ready", e);}t.traceEnd();t.traceBegin("MakeNetworkStatsServiceReady");try {if (networkStatsF != null) {networkStatsF.systemReady();}} catch (Throwable e) {reportWtf("making Network Stats Service ready", e);}t.traceEnd();t.traceBegin("MakeConnectivityServiceReady");try {if (connectivityF != null) {connectivityF.systemReady();}} catch (Throwable e) {reportWtf("making Connectivity Service ready", e);}t.traceEnd();t.traceBegin("MakeNetworkPolicyServiceReady");try {if (networkPolicyF != null) {networkPolicyF.systemReady(networkPolicyInitReadySignal);}} catch (Throwable e) {reportWtf("making Network Policy Service ready", e);}t.traceEnd();// Wait for all packages to be preparedmPackageManagerService.waitForAppDataPrepared();// It is now okay to let the various system services start their// third party code...t.traceBegin("PhaseThirdPartyAppsCanStart");// confirm webview completion before starting 3rd partyif (webviewPrep != null) {ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);}mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);t.traceEnd();t.traceBegin("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();} catch (Throwable e) {reportWtf("starting Network Stack", e);}t.traceEnd();t.traceBegin("StartTethering");try {// TODO: hide implementation details, b/146312721.ConnectivityModuleConnector.getInstance().startModuleService(TETHERING_CONNECTOR_CLASS,PERMISSION_MAINLINE_NETWORK_STACK, service -> {ServiceManager.addService(Context.TETHERING_SERVICE, service,false /* allowIsolated */,DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);});} catch (Throwable e) {reportWtf("starting Tethering", e);}t.traceEnd();t.traceBegin("MakeCountryDetectionServiceReady");try {if (countryDetectorF != null) {countryDetectorF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying CountryDetectorService running", e);}t.traceEnd();t.traceBegin("MakeNetworkTimeUpdateReady");try {if (networkTimeUpdaterF != null) {networkTimeUpdaterF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying NetworkTimeService running", e);}t.traceEnd();t.traceBegin("MakeInputManagerServiceReady");try {// TODO(BT) Pass parameter to input managerif (inputManagerF != null) {inputManagerF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying InputManagerService running", e);}t.traceEnd();t.traceBegin("MakeTelephonyRegistryReady");try {if (telephonyRegistryF != null) {telephonyRegistryF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying TelephonyRegistry running", e);}t.traceEnd();t.traceBegin("MakeMediaRouterServiceReady");try {if (mediaRouterF != null) {mediaRouterF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying MediaRouterService running", e);}t.traceEnd();t.traceBegin("MakeMmsServiceReady");try {if (mmsServiceF != null) {mmsServiceF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying MmsService running", e);}t.traceEnd();t.traceBegin("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);}t.traceEnd();if (mIncrementalServiceHandle != 0) {t.traceBegin("MakeIncrementalServiceReady");setIncrementalServiceSystemReady(mIncrementalServiceHandle);t.traceEnd();}}, t);}

SystemServer的startOtherServices()方法中的调用顺序为:

  1. code snippet 18:mActivityManagerService.installSystemProviders();
  2. code snippet 19:mActivityManagerService.setWindowManager(wm);
  3. code snippet 20:if (safeMode) mActivityManagerService.enterSafeMode();
  4. code snippet 21:if (sPendingWtfs != null)  mActivityManagerService.schedulePendingSystemServerWtfs(sPendingWtfs);
  5. code snippet 22:if (safeMode) mActivityManagerService.enterSafeMode();
  6. code snippet 23:mActivityManagerService.systemReady(() -> {

五、AMS和ATMS的接口简介

在AMS构造方法中,传进来一个参数为ActivityTaskManagerService atm。

从ActivityTaskManagerService的类注释System service for managing activities and their containers (task, stacks, displays,... ).可以清楚的看出:它是一个系统服务,用来管理activitys和它们的容器(如task, stacks, displays)

再从ActivityManagerService里找找ActivityTaskManagerService的使用:

Activity管理:

  1. mActivityTaskManager.startActivity();

  2. mActivityTaskManager.startActivityAsUser();

  3. mActivityTaskManager.startActivityAndWait();

  4. mActivityTaskManager.startActivityFromRecents();

  5. mActivityTaskManager.startRecentsActivity();

  6. mActivityTaskManager.finishActivity

Stack管理:

  1. mActivityTaskManager.setFocusedStack(stackId);

  2. mActivityTaskManager.removeStack(stackId);

  3. mActivityTaskManager.registerTaskStackListener(listener);//Sets the task stack listener that gets callbacks when a task stack changes.

Task管理:

  1. mActivityTaskManager.getTasks(maxNum);

  2. mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);

  3. mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);

  4. mActivityTaskManager.getTaskBounds(taskId);

  5. mActivityTaskManager.removeTask(taskId);

  6. mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);

  7. mActivityTaskManager.moveActivityTaskToBack(token, nonRoot);

  8. mActivityTaskManager.moveTaskToStack(taskId, stackId, toTop);

  9. mActivityTaskManager.positionTaskInStack(taskId, stackId, position);

  10. mActivityTaskManager.getTaskForActivity(token, onlyRoot);

  11. mActivityTaskManager.isTopOfTask(token);

初始化操作

  1. mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,DisplayThread.get().getLooper());

    • 详见ActivityManagerService构造方法

  2. mActivityTaskManager.installSystemProviders();

  3. mActivityTaskManager.setActivityController(controller, imAMonkey);

  4. mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);

    • 详见ActivityManagerService.setPackageScreenCompatMode()

Configuration和Orientation

  1. mActivityTaskManager.setRequestedOrientation(token, requestedOrientation);

    • 详见ActivityManagerService.setRequestedOrientation()

  2. mActivityTaskManager.updateConfiguration(values);

状态监听

  1. mActivityTaskManager.onActivityManagerInternalAdded();

    • 详见ActivityManagerService.start()

  2. mActivityTaskManager.onScreenAwakeChanged(isAwake);

在AMS的setWindowManager(WindowManagerService wm) 方法把WindowManagerService设置给了变量 mWindowManager。

WindowManagerService在AMS的使用不多:

    public void setWindowManager(WindowManagerService wm) {synchronized (this) {mWindowManager = wm;mWmInternal = LocalServices.getService(WindowManagerInternal.class);mActivityTaskManager.setWindowManager(wm);}}

在AMS的setWindowManager方法直接又传给了ActivityTaskManagerService

从当前AMS出生地这个视角,能看到这些。能看出来在AMS使用最多的是ActivityTaskManagerService。AMS的很多接口功能直接是ActivityTaskManagerService实现的。

这篇文章的目的是从一个视角整理类的设计理念,功能和类之前的关联,达到在脑子里有一个整体的架构。因此不去研究各个方法的具体实现。

角色图:

下面针对上面的分析画一个角色图:

问题:

从上面的角色图可以看到三个概念:

  • Task
  • Stack
  • WindowManager

要想研究明白Android的Activity和Window管理,接下来肯定要花些时间研究一下:

  1. ActivityTaskManagerService
  2. 什么是Task
  3. 什么是Stack
  4. Window的管理

Android11 AMS的出生地到此一游相关推荐

  1. framework之Activity启动流程(基于Android11源码)

    一步步看,你就会对activity的启动流程有深刻的认知. 引言 Android11上,Activity的启动流程与Android10的实现(可以参考Activity的启动过程详解(基于10.0源码) ...

  2. 对HDS AMS 2000+巡检案例

    1.       使用工具:笔记本,网线一根, 2.       使用软件:vmware虚拟机(安装XP P2系统,最好为P3),HSNM2-1152-W-CLI-P01.exe(AMS 200管理软 ...

  3. eoLinker AMS 专业版V3.3发布:分享项目可以测试并选择分享内容等

    eoLinker AMS是集API文档管理.API自动化测试.开发协作三位一体的综合API开发管理平台,是中国最大的在线API管理平台.目前eoLinker AMS已经为来自全球的超过两万家企业托管超 ...

  4. 日请求亿级的QQ会员AMS平台PHP7升级实践

    QQ会员活动运营平台(AMS),是QQ会员增值运营业务的重要载体之一,承担海量活动运营的Web系统.AMS是一个主要采用PHP语言实现的活动运营平台, CGI日请求3亿左右,高峰期达到8亿.然而,在之 ...

  5. AMS重要的数据结构解析(三):ActivityStack

    最近以Android-28为基础,梳理了一下Activity的启动过程,在此做一些学习笔记.方便需要时查阅. 此次主要关注"从Laucher点击一个app图标A ,到A 启动Applicat ...

  6. AMS重要的数据结构解析(二):TaskRecord

    Android依托Java型虚拟机,OOM是经常遇到的问题,那么在快达到OOM的时候,系统难道不能回收部分界面来达到缩减开支的目的码?在系统内存不足的情况下,可以通过AMS及LowMemoryKill ...

  7. 【Android 启动过程】Activity 启动源码分析 ( AMS -> ActivityThread、AMS 线程阶段 二 )

    文章目录 前言 一.热启动与冷启动选择 二.AMS 进程中执行的相关操作 三.通过 Binder 机制转到 ActivityThread 中执行的操作 总结 前言 上一篇博客 [Android 启动过 ...

  8. 【Android 启动过程】Activity 启动源码分析 ( AMS -> ActivityThread、AMS 线程阶段 )

    文章目录 一.Activity 启动源码分析 ( AMS | ActivityManagerService ) 1.Instrumentation 调用 AMS 方法 2.ActivityStarte ...

  9. 【Android 启动过程】Activity 启动源码分析 ( Activity -> AMS、主线程阶段 )

    文章目录 一.Activity 启动源码分析 ( Activity -> AMS 阶段 ) 一.Activity 启动源码分析 ( Activity -> AMS 阶段 ) 调用 star ...

最新文章

  1. python将string转换为json_python -- 将string转换成dict的方法
  2. Java网络编程——11.非阻塞I/O
  3. SqlServer2005数据库分区
  4. python 吧-做为IT人的你 趁年轻学点Python吧
  5. my wordpress
  6. c4d流体插件_(图文+视频)C4D野教程:TFD、XP和RF三大流体插件协作案例
  7. java基础—List集合的常规方法操作
  8. PHP面向对象知识点
  9. activity劫持反劫持
  10. 《英雄联盟》“被手游”背后,是移动电竞的成长期“烦恼”
  11. wps序号打乱重新排序_wps表格 已经排好序号 ,顺序错误,想重新排列
  12. 有哪些方法能将纸质书籍转成PDF电子版
  13. 学计算机基础的重要性,浅谈学习计算机基础知识的重要性.pdf
  14. pca图解读_主成分分析pca图解读,主成分分析散点图解读
  15. 案例:恒丰银行——大数据实时流处理平台
  16. redmine backlogs的tracker使用
  17. ImageNet-1k分类数据集中英对照表 验证集类别解析
  18. ol+天地图+geoserver_教程:使用GeoServer发布离线地图服务(WMS)
  19. .NET 6 实现滑动验证码(七)、生成验证码
  20. Java常用设计模式-策略模式

热门文章

  1. 自娱自乐写爬虫 世纪佳缘篇
  2. php字符串转数组,数组合并成字符串
  3. SQL注入系列(一)——超详细SQL注入环境搭建
  4. 帮企业省钱,让个人经营者更合规,灵活用工系统开发未来可期!
  5. Linux usb设备驱动
  6. 中国艺术《先得月》孙溟㠭篆刻作品
  7. Unity-2D游戏开发套件指南-免费资源
  8. 高德地图经纬度和百度地图经纬度互相转换
  9. 职高计算机动漫设计专业就业困难,动漫设计专业就业怎么样?可以找哪些工作?...
  10. 记录一次公司生产服务器被前端程序猿 rm -rf /的血泪恢复史