- 4.1 前言
- 4.2 启动
- 4.3 AMS.start
- 4.4 AMS.setSystemProcess
- 4.5 startOtherServices
- 4.6 ActivityManagerService.systemReady
4.1 前言
前面已经提到过在SystemServer中启动了AMS,并且AMS是android系统中很重要的服务.记录着Activity的
开启,关闭,以及一些记录,同时我们所能看到的launcher也是通过AMS启动的。
源码:
<http://androidxref.com/9.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java>
4.2 启动
AMS是在SystemServer中创建的,只copy出来了主要代码
private void startBootstrapServices() {
// Activity manager runs the show.
558 traceBeginAndSlog("StartActivityManager");
//实例化对象
559 mActivityManagerService = mSystemServiceManager.startService(
560 ActivityManagerService.Lifecycle.class).getService();
//把自己添加为binder service,从而别的进程调用
mActivityManagerService.setSystemProcess();
}
先看下Lifecycle这个类是干嘛的,继承了SystemService,然后在构造函数中把AMS的对象实例化出来
public static final class Lifecycle extends SystemService {
2878 private final ActivityManagerService mService;
2879
2880 public Lifecycle(Context context) {
2881 super(context);
2882 mService = new ActivityManagerService(context);
2883 }
2884
2885 @Override
2886 public void onStart() {
2887 mService.start();
2888 }
2889
2890 @Override
2891 public void onBootPhase(int phase) {
2892 mService.mBootPhase = phase;
2893 if (phase == PHASE_SYSTEM_SERVICES_READY) {
2894 mService.mBatteryStatsService.systemServicesReady();
2895 mService.mServices.systemServicesReady();
2896 }
2897 }
2898
2899 @Override
2900 public void onCleanupUser(int userId) {
2901 mService.mBatteryStatsService.onCleanupUser(userId);
2902 }
2903
2904 public ActivityManagerService getService() {
2905 return mService;
2906 }
2907 }
接着看SystemServiceManager的startService方法,在这个方法里面通过反射实例化了lifecycle这个类
*/
83 @SuppressWarnings("unchecked")
84 public <T extends SystemService> T startService(Class<T> serviceClass) {
85 try {
86 final String name = serviceClass.getName();
87 Slog.i(TAG, "Starting " + name);
88 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
89
90 // Create the service.
91 if (!SystemService.class.isAssignableFrom(serviceClass)) {
92 throw new RuntimeException("Failed to create " + name
93 + ": service must extend " + SystemService.class.getName());
94 }
95 final T service;
96 try {
//通过构造函数实例化lifecycle对象
97 Constructor<T> constructor = serviceClass.getConstructor(Context.class);
98 service = constructor.newInstance(mContext);
99 } catch (InstantiationException ex) {
100 throw new RuntimeException("Failed to create service " + name
101 + ": service could not be instantiated", ex);
102 } catch (IllegalAccessException ex) {
103 throw new RuntimeException("Failed to create service " + name
104 + ": service must have a public constructor with a Context argument", ex);
105 } catch (NoSuchMethodException ex) {
106 throw new RuntimeException("Failed to create service " + name
107 + ": service must have a public constructor with a Context argument", ex);
108 } catch (InvocationTargetException ex) {
109 throw new RuntimeException("Failed to create service " + name
110 + ": service constructor threw an exception", ex);
111 }
112
113 startService(service);
114 return service;
115 } finally {
116 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
117 }
118 }
//调用lifecycle的onstart方法,也就是调用AMS的onStart方法
public void startService(@NonNull final SystemService service) {
121 // Register it.
122 mServices.add(service);
123 // Start it.
124 long time = SystemClock.elapsedRealtime();
125 try {
126 service.onStart();
127 } catch (RuntimeException ex) {
128 throw new RuntimeException("Failed to start service " + service.getClass().getName()
129 + ": onStart threw an exception", ex);
130 }
131 warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
132 }
到这里AMS的对象通过lifecycle实例化了。并且onStart方法开始运行了,我们来看看AMS里面是怎么实例化的
// handlers to other threads. So take care to be explicit about the looper.
3047 public ActivityManagerService(Context systemContext) {
3048 LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
3049 mInjector = new Injector();
3050 mContext = systemContext;
3051
3052 mFactoryTest = FactoryTest.getMode();
3053 mSystemThread = ActivityThread.currentActivityThread();
3054 mUiContext = mSystemThread.getSystemUiContext();
3055
3056 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
3057
3058 mPermissionReviewRequired = mContext.getResources().getBoolean(
3059 com.android.internal.R.bool.config_permissionReviewRequired);
3060 /创建名为"ActivityManager"的前台线程,并获取mHandler
3061 mHandlerThread = new ServiceThread(TAG,
3062 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
3063 mHandlerThread.start();
3064 mHandler = new MainHandler(mHandlerThread.getLooper());
3065 mUiHandler = mInjector.getUiHandler(this);
3066
3067 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
3068 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
3069 mProcStartHandlerThread.start();
3070 mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
3071
3072 mConstants = new ActivityManagerConstants(this, mHandler);
3073
3074 /* static; one-time init here */
3075 if (sKillHandler == null) {
3076 sKillThread = new ServiceThread(TAG + ":kill",
3077 THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
3078 sKillThread.start();
3079 sKillHandler = new KillHandler(sKillThread.getLooper());
3080 }
3081
//前台广播接收器,超时时间为10S
3082 mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
3083 "foreground", BROADCAST_FG_TIMEOUT, false);
//后台广播接收器,超时时间为60S
3084 mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
3085 "background", BROADCAST_BG_TIMEOUT, true);
3086 mBroadcastQueues[0] = mFgBroadcastQueue;
3087 mBroadcastQueues[1] = mBgBroadcastQueue;
3088
3089 mServices = new ActiveServices(this);
3090 mProviderMap = new ProviderMap(this);
3091 mAppErrors = new AppErrors(mUiContext, this);
3092
//创建目录/data/system
3093 File dataDir = Environment.getDataDirectory();
3094 File systemDir = new File(dataDir, "system");
3095 systemDir.mkdirs();
3096
3097 mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler, systemDir);
3098 //创建服务BatteryStatsService
3099 // TODO: Move creation of battery stats service outside of activity manager service.
3100 mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
3101 mBatteryStatsService.getActiveStatistics().readLocked();
3102 mBatteryStatsService.scheduleWriteToDisk();
3103 mOnBattery = DEBUG_POWER ? true
3104 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
3105 mBatteryStatsService.getActiveStatistics().setCallback(this);
3106
//创建进程统计服务,信息保存在目录/data/system/procstats,
3107 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
3108
3109 mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
3110
3111 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
3112
3113 mUserController = new UserController(this);
3114
3115 mVrController = new VrController(this);
3116
3117 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
3118 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
3119
3120 if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
3121 mUseFifoUiScheduling = true;
3122 }
3123
3124 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
3125 mTempConfig.setToDefaults();
3126 mTempConfig.setLocales(LocaleList.getDefault());
3127 mConfigurationSeq = mTempConfig.seq = 1;
3128 mStackSupervisor = createStackSupervisor();
3129 mStackSupervisor.onConfigurationChanged(mTempConfig);
3130 mKeyguardController = mStackSupervisor.getKeyguardController();
3131 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
3132 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
3133 mTaskChangeNotificationController =
3134 new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
3135 mActivityStartController = new ActivityStartController(this);
3136 mRecentTasks = createRecentTasks();
3137 mStackSupervisor.setRecentTasks(mRecentTasks);
3138 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);
3139 mLifecycleManager = new ClientLifecycleManager();
3140
//创建名为"CpuTracker"的线程
3141 mProcessCpuThread = new Thread("CpuTracker") {
3142 @Override
3143 public void run() {
3144 synchronized (mProcessCpuTracker) {
3145 mProcessCpuInitLatch.countDown();
3146 mProcessCpuTracker.init();
3147 }
3148 while (true) {
3149 try {
3150 try {
3151 synchronized(this) {
3152 final long now = SystemClock.uptimeMillis();
3153 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
3154 lon g nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
3155 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
3156 // + ", write delay=" + nextWriteDelay);
3157 if (nextWriteDelay < nextCpuDelay) {
3158 nextCpuDelay = nextWriteDelay;
3159 }
3160 if (nextCpuDelay > 0) {
3161 mProcessCpuMutexFree.set(true);
3162 this.wait(nextCpuDelay);
3163 }
3164 }
3165 } catch (InterruptedException e) {
3166 }
//更新CPU的状态
3167 updateCpuStatsNow();
3168 } catch (Exception e) {
3169 Slog.e(TAG, "Unexpected exception collecting process stats", e);
3170 }
3171 }
3172 }
3173 };
3174
3175 mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
3176
3177 Watchdog.getInstance().addMonitor(this);
3178 Watchdog.getInstance().addThread(mHandler);
3179
3180 // bind background thread to little cores
3181 // this is expected to fail inside of framework tests because apps can't touch cpusets directly
3182 // make sure we've already adjusted system_server's internal view of itself first
3183 updateOomAdjLocked();
3184 try {
3185 Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
3186 Process.THREAD_GROUP_BG_NONINTERACTIVE);
3187 } catch (Exception e) {
3188 Slog.w(TAG, "Setting background thread cpuset failed");
3189 }
3190
3191 }
4.3 AMS.start
private void start() {
//移除所有的进程组
3216 removeAllProcessGroups();
//CpuTracker线程开启
3217 mProcessCpuThread.start();
3218 //启动电池统计服务
3219 mBatteryStatsService.publish();
3220 mAppOpsService.publish(mContext);
3221 Slog.d("AppOps", "AppOpsService published");
//添加到本地的service,这个地方只能在同一个进程里面可以调用,这个地方很重要,因为下面还有一个binder service
3222 LocalServices.addService(ActivityManagerInternal.class, new LocalService());
3223 // Wait for the synchronized block started in mProcessCpuThread,
3224 // so that any other acccess to mProcessCpuTracker from main thread
3225 // will be blocked during mProcessCpuTracker initialization.
3226 try {
3227 mProcessCpuInitLatch.await();
3228 } catch (InterruptedException e) {
3229 Slog.wtf(TAG, "Interrupted wait during start", e);
3230 Thread.currentThread().interrupt();
3231 throw new IllegalStateException("Interrupted wait during start");
3232 }
3233 }
4.4 AMS.setSystemProcess
在systemserver类的startBootstrapServices方法会调用setSystemProcess方法,这里有一个地方很重要
我也是找了半天才看出来, 添加binder service,为跨进程通信使用,我当时纳闷了好久,因为在ActivityManager中
会用到这个binder service,我找了很长时间才找到
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL |
这个方法里面主要就是注册各种服务
public void setSystemProcess() {
2721 try {
2722 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2723 DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2724 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2725 ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2726 DUMP_FLAG_PRIORITY_HIGH);
2727 ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2728 ServiceManager.addService("dbinfo", new DbBinder(this));
2729 if (MONITOR_CPU_USAGE) {
2730 ServiceManager.addService("cpuinfo", new CpuBinder(this),
2731 /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2732 }
2733 ServiceManager.addService("permission", new PermissionController(this));
2734 ServiceManager.addService("processinfo", new ProcessInfoService(this));
2735
2736 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2737 "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2738 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2739
2740 synchronized (this) {
2741 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2742 app.persistent = true;
2743 app.pid = MY_PID;
2744 app.maxAdj = ProcessList.SYSTEM_ADJ;
2745 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2746 synchronized (mPidsSelfLocked) {
2747 mPidsSelfLocked.put(app.pid, app);
2748 }
2749 updateLruProcessLocked(app, false, null);
2750 updateOomAdjLocked();
2751 }
2752 } catch (PackageManager.NameNotFoundException e) {
2753 throw new RuntimeException(
2754 "Unable to find android system package", e);
2755 }
2756
2757 // Start watching app ops after we and the package manager are up and running.
2758 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2759 new IAppOpsCallback.Stub() {
2760 @Override public void opChanged(int op, int uid, String packageName) {
2761 if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2762 if (mAppOpsService.checkOperation(op, uid, packageName)
2763 != AppOpsManager.MODE_ALLOWED) {
2764 runInBackgroundDisabled(uid);
2765 }
2766 }
2767 }
2768 });
2769 }
4.5 startOtherServices
//在systemserer里面调用AMS的systemready方法
private void startOtherServices() {
mActivityManagerService.systemReady(new goingCallback()) {
startSystemUi();
}
}
4.6 ActivityManagerService.systemReady
这里大概的流程
public void systemReady(final Runnable goingCallback) {
...//更新操作
mSystemReady = true; //系统处于ready状态
removeProcessLocked(proc, true, false, "system update done");//杀掉所有非persistent进程
mProcessesReady = true; //进程处于ready状态
goingCallback.run(); //这里有可能启动进程。这里会启动systemui
addAppLocked(info, false, null); //启动所有的persistent进程
mBooting = true; //正在启动中
startHomeActivityLocked(mCurrentUserId, "systemReady"); //启动launcher
mStackSupervisor.resumeTopActivitiesLocked(); //恢复栈顶的Activity
}
大致的流程:
忽略我的没有注册的staruml软件 ==!