6.long lastCpuTime // How long proc has run CPU at last check
7.long curCpuTime: // How long proc has run CPU most recently
8.long lastRequestedGc: // When we last asked the app to do a gc
9.long lastLowMemory: // When we last told the app that memory is low
10.long lastProviderTime: // The last time someone else was using a provider in this process.
11.long interactionEventTime: // The time we sent the last interaction event
12.long fgInteractionTime: // When we became foreground for interaction purposes
第六类数据:描述 Crash、ANR
1.IBinder.DeathRecipient deathRecipient: // Who is watching for the death.【apk进程退出运行的话,会触发这个对象的binderDied()方法,来回收系统资源】
2.boolean crashing: // are we in the process of crashing?【进程是否已经 crash】
3.Dialog crashDialog: // dialog being displayed due to crash.【crash对话框】
4.boolean forceCrashReport: // suppress normal auto-dismiss of crash dialog & report UI?【强制crash对话框显示】
5.boolean notResponding: // does the app have a not responding dialog?【是否处于ANR状态】
6.Dialog anrDialog: // dialog being displayed due to app not resp.【ANR显示对话框】
7.Runnable crashHandler: // Optional local handler to be invoked in the process crash.【crash回调】
8.ActivityManager.ProcessErrorStateInfo crashingReport: // These reports are generated & stored when an app gets into an error condition. They will be “null” when all is OK.【crash报告的进程状态】
9.ActivityManager.ProcessErrorStateInfo notRespondingReport: // These reports are generated & stored when an app gets into an error condition. They will be “null” when all is OK.【ANR报告的进程状态】
10.String waitingToKill: // Process is waiting to be killed when in the bg, and reason【后台进程被kill原因】
11.ComponentName errorReportReceiver: // Who will be notified of the error. This is usually an activity in the app that installed the package.【接收error信息的组件】
final ActivityManagerService service; // owner final IApplicationToken.Stub appToken; // window manager token AppWindowContainerController mWindowContainerController; final ActivityInfo info; // all about me // TODO: This is duplicated state already contained in info.applicationInfo - remove ApplicationInfo appInfo; // information about activity's app
... ...
//ActivityRecord所在的TaskRecord private TaskRecord task; // the task this is in.
finalint taskId; // Unique identifier for this task. 任务ID
...
/** List of all activities in the task arranged in history order */ final ArrayList<ActivityRecord> mActivities; // 使用一个ArrayList来保存所有的 ActivityRecord
/** Current stack. Setter must always be used to update the value. */ private ActivityStack mStack; // TaskRecord所在的 ActivityStack
...
/** * Don't use constructor directly. Use {@link #create(ActivityManagerService, int, ActivityInfo, * Intent, TaskDescription)} instead. */ TaskRecord(ActivityManagerService service, int _taskId, ActivityInfo info, Intent _intent, IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) { }
/** * Don't use constructor directly. Use {@link #create(ActivityManagerService, int, ActivityInfo, * Intent, IVoiceInteractionSession, IVoiceInteractor)} instead. */ TaskRecord(ActivityManagerService service, int _taskId, ActivityInfo info, Intent _intent, TaskDescription _taskDescription) { }
/** * Don't use constructor directly. This is only used by XML parser. */ TaskRecord(ActivityManagerService service, int _taskId, Intent _intent, Intent _affinityIntent, String _affinity, String _rootAffinity, ComponentName _realActivity, ComponentName _origActivity, boolean _rootWasReset, boolean _autoRemoveRecents, boolean _askedCompatMode, int _userId, int _effectiveUid, String _lastDescription, ArrayList<ActivityRecord> activities, long lastTimeMoved, boolean neverRelinquishIdentity, TaskDescription _lastTaskDescription, int taskAffiliation, int prevTaskId, int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, int resizeMode, boolean supportsPictureInPicture, boolean _realActivitySuspended, boolean userSetupComplete, int minWidth, int minHeight) { }
/** * Controller for interpreting how and then launching an activity. * * This class collects all the logic for determining how an intent and flags should be turned into * an activity and associated task and stack. */ classActivityStarter{ privateintsetTaskFromReuseOrCreateNewTask( TaskRecord taskToAffiliate, ActivityStack topStack){ mTargetStack = computeStackFocus(mStartActivity, true, mLaunchFlags, mOptions);
// Do no move the target stack to front yet, as we might bail if // isLockTaskModeViolation fails below.
/** * State and management of a single stack of activities. */ classActivityStack<TextendsStackWindowController> extendsConfigurationContainer implementsStackWindowListener{ /** * The back history of all previous (and possibly still * running) activities. It contains #TaskRecord objects. */ privatefinal ArrayList<TaskRecord> mTaskHistory = new ArrayList<>(); // ArrayList 保存 TaskRecord
/** Run all ActivityStacks through this */ protectedfinal ActivityStackSupervisor mStackSupervisor; // 持有一个 ActivityStackSupervisor,所有的运行中的 ActivityStacks 都通过它来进行管
/** The stack containing the launcher app. Assumed to always be attached to * Display.DEFAULT_DISPLAY. */ ActivityStack mHomeStack; // 管理的是 Launcher 相关的任务
/** The stack currently receiving input or launching the next activity. */ ActivityStack mFocusedStack; //管理非 Launcher相关的任务
// 创建系统服务管理器 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.get(); } finally { traceEnd(); // InitBeforeStartServices }
// Now that the power manager has been started, let the activity manager // initialize power management features. traceBeginAndSlog("InitPowerManagement"); mActivityManagerService.initPowerManagement(); traceEnd();
...
// Set up the Application instance for the system process and get started. traceBeginAndSlog("SetSystemProcess"); mActivityManagerService.setSystemProcess(); traceEnd();
@SuppressWarnings("unchecked") public SystemService startService(String className){ final Class<SystemService> serviceClass; try { serviceClass = (Class<SystemService>)Class.forName(className); } catch (ClassNotFoundException ex) { Slog.i(TAG, "Starting " + className); thrownew RuntimeException("Failed to create service " + className + ": service class not found, usually indicates that the caller should " + "have called PackageManager.hasSystemFeature() to check whether the " + "feature is available on this device before trying to start the " + "services that implement it", ex); } return startService(serviceClass); }
@SuppressWarnings("unchecked") 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)) { thrownew RuntimeException("Failed to create " + name + ": service must extend " + SystemService.class.getName()); } final T service; try { Constructor<T> constructor = serviceClass.getConstructor(Context.class); service = constructor.newInstance(mContext); } catch (InstantiationException ex) { thrownew RuntimeException("Failed to create service " + name + ": service could not be instantiated", ex); } catch (IllegalAccessException ex) { thrownew RuntimeException("Failed to create service " + name + ": service must have a public constructor with a Context argument", ex); } catch (NoSuchMethodException ex) { thrownew RuntimeException("Failed to create service " + name + ": service must have a public constructor with a Context argument", ex); } catch (InvocationTargetException ex) { thrownew RuntimeException("Failed to create service " + name + ": service constructor threw an exception", ex); }
publicvoidstartService(@NonNull final SystemService service){ // Register it. mServices.add(service); // Start it. long time = SystemClock.elapsedRealtime(); try { service.onStart(); } catch (RuntimeException ex) { thrownew RuntimeException("Failed to start service " + service.getClass().getName() + ": onStart threw an exception", ex); } warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart"); }
startService 是通过传进来的 class 参数然后反射创建对应的 service 服务。所以此处创建的是 Lifecycle 的实例,然后通过 startService 启动 AMS服务。
public ActivityManagerService getService(){ return mService; } }
AMS Constructor
再看 AMS 构造函数初始化
// 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. publicActivityManagerService(Context systemContext){ LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY); mInjector = new Injector(); // 赋值 上下文环境 mContext = systemContext;
mBatteryStatsService.publish(); mAppOpsService.publish(mContext); Slog.d("AppOps", "AppOpsService published"); LocalServices.addService(ActivityManagerInternal.class, newLocalService()); // Wait for the synchronized block started in mProcessCpuThread, // so that any other acccess to mProcessCpuTracker from main thread // will be blocked during mProcessCpuTracker initialization. // 等待 mProcessCpuThread 完成初始化后释放锁,初始化期间禁止访问 try { mProcessCpuInitLatch.await(); } catch (InterruptedException e) { Slog.wtf(TAG, "Interrupted wait during start", e); Thread.currentThread().interrupt(); thrownew IllegalStateException("Interrupted wait during start"); } }
setSystemProcess
在 AMS 启动完成后,再来看 setSystemProcess 方法
publicvoidsetSystemProcess(){ try { // 注册服务 // 先将 ActivityManagerService 注册到 ServiceManager 中, // 其次将几个与系统性能调试相关的几个服务也注册到 ServiceManager中 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 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)); ServiceManager.addService("processinfo", new ProcessInfoService(this));
// 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() { @OverridepublicvoidopChanged(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); } } } }); }