AMS 透過 SystemServiceManager 來啟動#
public final class SystemServer implements Dumpable {
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
... 省略部分
try {
t.traceBegin("StartServices");
// AMS 是引導服務
startBootstrapServices(t); // 啟動引導服務
startCoreServices(t); // 啟動核心服務
startOtherServices(t); // 啟動其他服務
startApexServices(t); // 啟動Apex服務
} /*省略 catch*/
... 省略部分
}
// 啟動 AMS 的函數
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
... 省略部分
// Activity manager runs the show.
// 相當於創建了一個 ActivityTaskManagerService 類
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
// 分析 ActivityManagerService.Lifecycle.startService
mActivityManagerService = ActivityManagerService
.Lifecycle.startService( // startService 會呼叫 onStart 方法
mSystemServiceManager,
atm
);
... 省略部分
// 之後分析
mActivityManagerService.setSystemProcess();
... 省略部分
}
}
AMS 透過 AMS#Lifecycle
內部類創建#
// ActivityManagerService.java
// 繼承於 SystemService (抽象類)
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
// 創建 AMS
mService = new ActivityManagerService(context, sAtm);
}
// SystemService#startService 會呼叫到 onStart 方法
@Override
public void onStart() {
// AMS 私有函數 start()
mService.start();
}
... 省略部分
}
SystemService#startService
呼叫 onStart 方法#
// ActivityManagerService.java
private void start() {
// 啟動電池統計服務
mBatteryStatsService.publish();
mAppOpsService.publish();
Slog.d("AppOps", "AppOpsService published");
// 添加到本地 LocalServices 中
LocalServices.addService(ActivityManagerInternal.class, mInternal);
LocalManagerRegistry.addManager(ActivityManagerLocal.class,
(ActivityManagerLocal) mInternal);
mActivityTaskManager.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
mAppProfiler.onActivityManagerInternalAdded();
}
構造函數#
// /services/core/java/com/android/server/am/ActivityManagerService.java
// AMS 構建函數
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector(systemContext);
// 系統級 Context
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
// 獲取當前的 ActiivtyThread
mSystemThread = ActivityThread.currentActivityThread();
// 取得 系統 UiContext
mUiContext = mSystemThread.getSystemUiContext();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
// 創建 Handler Thread 處理 Handler 消息
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
// 處理 UI 相關訊息的 Handler
mUiHandler = mInjector.getUiHandler(this);
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
// 進程啟動的 Handler
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
// 管理 AMS 的常量,廠商制定系統就有可能修改此處
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);
mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
new LowMemDetector(this));
mPhantomProcessList = new PhantomProcessList(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;
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 queue
offloadConstants.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);
mBgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
"offload_bg", offloadConstants, true);
mFgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
"offload_fg", foreConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mBroadcastQueues[2] = mBgOffloadBroadcastQueue;
mBroadcastQueues[3] = mFgOffloadBroadcastQueue;
// 初始化管理 Services 的 ActiveServices 物件
mServices = new ActiveServices(this);
// 初始化 ContentProvider
mCpHelper = new ContentProviderHelper(this, true);
// 包 WatchDog
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
// 初始化 APP 錯誤日誌記錄組件
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
mUidObserverController = new UidObserverController(mUiHandler);
// 取得系統資料夾
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);
// 初始化系統屬性
mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
// 賦予 ActivityTaskManager
mActivityTaskManager = atm;
// 初始化,內部會創建 ActivityStackSupervisor 類
// ActivityStackSupervisor 會記錄 Activity 狀態信息,是 AMS 的核心類
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
DisplayThread.get().getLooper());
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
mSdkSandboxSettings = new SdkSandboxSettings(mContext);
// Watchdog 監聽(若進程不正常則會被 Kill)
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.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);
mTraceErrorLogger = new TraceErrorLogger();
mComponentAliasResolver = new ComponentAliasResolver(this);
}
AMS#setSystemProcess
方法不只註冊自己 (AMS) 的 Server 到 Binder 驅動中,而是一系列與進程相關的服務,下表會提及幾個常見的服務項目
// /ActivityManagerService.java
public void setSystemProcess() {
try {
// 註冊 AMS
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
// 註冊 ProcessStatsService
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));
ServiceManager.addService("cacheinfo", new CacheBinder(this));
// 調用 PackageManagerService 的接口,查詢包名為 android 的應用 App 的 ApplicationInfo 訊息
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
// 往下分析 Activity#installSystemApplicationInfo 函數
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
// 創建 ProcessRecord 對象,並保存 AMS 對象訊息
synchronized (this) {
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
false,
0,
new HostingRecord("system"));
app.setPersistent(true);
app.setPid(MY_PID);
app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
addPidLocked(app);
updateLruProcessLocked(app, false, null);
updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
}
... 省略部分
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
... 省略部分
}
Binder - AMS 功能#
要知道所有的 AMS 功能最好是去查詢 IActivityManager,它裡面包含所有 AMS 所提供的功能,以下分為幾種分類描述
組件狀態 - 管理: 4 大組件的管理,startActivity、startActivityAndWait、startService、stopService、removeContentProvider … 等等
組件狀態 - 查詢: 查看當前組件的運行狀況 getCallingAcitivty、getServices… 等等
Task 相關: Task 相關的函數,removeSubTask、remove Task … 等等
其他: getMemoryInfo、setDebugApp… 等等
AMS 重點類#
AMS 相關類 | 功能 |
---|---|
ActivityStackSupervisor | 管理 Activity Stack |
ClientLifecycleManager | Android 28 之後才加入,用來控制管理 Activity 的生命周期 |
ActivityStart | Activity 啟動器,也管理 Activity 的啟動細節 |
ActivityStartController | 產生 ActivityStart 的實例,並且複用 |
ActivityTaskManagerService (簡稱 ATMS) | Android 核心服務,負責啟動四大組件 |
ActivityTaskManager | Activity 與 ATMS 跨進程通訊的接口,是 ATMS 的輔助類 |
ProcessRecord | 描述身份的數據 |
RecentTasks | 最近開啟的 Activity |
App 相關類 | 功能 |
---|---|
ActivityThread | App 應用的進入點,啟動主線程 |
ActivityThread#ApplicationThread | ApplicationThread 是 ActivityThread 的內部類,繼承 IApplication.Sub,它作為 APP 與 AMS 通訊的 Service 端 |
Instrumentation | Hook Activity 的啟動、結束… 等等操作,應用 APP 與 AMS 的互動都透過 Instrumentation |
ActivityStack | 以 Stack 為單位 (AndroidManifest 的四種啟動方式有關),負責管理多個 Activity |
ProcessRecord 進程管理#
ProcessRecord 類 - 進程相關訊息
參數 | 說明 |
---|---|
info : ApplicationInfo | AndroidManifest.xml 中定義的 <\application> tag 相關信息 |
isolated : Boolean | isolated 進程 |
uid : int | user id |
pid : int | 進程 process id |
gids : int[] | 群組 id |
userId : int | android 的多用戶系統 id (就像是 windows 的多位使用者功能) |
processName : String | 進程名,默認使用包名 |
uidRecord : UidRecord | 記錄以使用的 uid |
thread : IApplicationThread | 通過該物件 AMS 對 APP 發送訊息,該對象不為空代表該 APK 可使用 |
procStatFile:String | proc 目錄下每一個進程都有一個 以 pid 命名的目錄文件,該文件記錄進程的所有相關訊息,該目錄是 Linux Kernel 創建的 |
compat : CompatibilityInfo | 兼容性信息 |
requiredAbi : String | abi 訊息 |
instructionSet : String | 指令集合 |
mPkgDeps : ArraySet | 當前進程運行依賴的包 |
ProcessRecord 類 - 描述進程組件
參數 | 說明 |
---|---|
maxAdj : int | 進程的 Adj 上限 (adjustment) |
curRawAdj : int | 正在計算的 adj,這個值可能大於 maxAdj |
ProcessRecord 類 - 描述進程組件(四大零組件相關)
參數 | 說明 | 其他 |
---|---|---|
mWindowProcessController : WindowProcessController | 透過 WindowProcessController 管理所有 Activity | Activity 用 ActivityRecord 來表示 |
mServices : ProcessServiceRecord | 該進程內所有的 Service | Service 用 ServiceRecord 來表示 |
mProviders : ProcessProviderRecord | 該進程內所有的 Provider | ContentProvider 用 ContentProviderRecord 來表示 |
mReceivers : ProcessReceiverRecord | 該進程內所有的 Receiver | ContentProvider 用 BroadcastRecord 來表示 |
ActivityRecord - Activity#
ActivityRecord 在記錄一個 Activity 的所有訊息,它是 歷史棧中的一個 Activity,內部記錄 ActivityInfo (AndroidManifest 設定)、task 服務
final class ActivityRecord extends WindowToken implements WindowManagerService.AppFreezeListener {
// 所屬的 Task 服務
final ActivityTaskManagerService mAtmService;
// AndroidManifest 設定的數值
final ActivityInfo info;
// WindowsManager token
final ActivityRecord.Token appToken;
// 私有化構造函數
// 透過 builder 模式建構 ActivityRecord 對象
private ActivityRecord(ActivityTaskManagerService _service, WindowProcessController _caller,
int _launchedFromPid, int _launchedFromUid, String _launchedFromPackage,
@Nullable String _launchedFromFeature, Intent _intent, String _resolvedType,
ActivityInfo aInfo, ... /* 省略部份*/ ) {
... 省略部分
}
}
// ActivityStarter.java
// Last activity record we attempted to start
private ActivityRecord mLastStartActivityRecord;
private int executeRequest(Request request) {
...省略 Request 分析
// 透過 Builder 創建 AcitiviyRecord
final ActivityRecord r = new ActivityRecord.Builder(mService)
.setCaller(callerApp) // 設定各種參數
.setLaunchedFromPid(callingPid)
.setLaunchedFromUid(callingUid)
.setLaunchedFromPackage(callingPackage)
.setLaunchedFromFeature(callingFeatureId)
.setIntent(intent)
.setResolvedType(resolvedType)
.setActivityInfo(aInfo)
.setConfiguration(mService.getGlobalConfiguration())
.setResultTo(resultRecord)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setComponentSpecified(request.componentSpecified)
.setRootVoiceInteraction(voiceSession != null)
.setActivityOptions(checkedOptions)
.setSourceRecord(sourceRecord)
.build();
// 當前 Activity
mLastStartActivityRecord = r;
... 省略部分
}
啟動 Activity - 呼叫 ActivityTaskManagerService#
ActivityTaskManagerService 它也是一個系統服務(註冊在 Binde r 驅動中),App 端如果要呼叫就必須透過代理,這個代理就是 ActivityTaskManager
// Activity.java
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
...省略部分接口 {
/*package*/ ActivityThread mMainThread;
private Instrumentation mInstrumentation;
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
... 省略部分
// @ 分析 startActivityForResult 方法
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
// @ 分析 execStartActivity 方法
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this,
// ApplicationThread
mMainThread.getApplicationThread(),
mToken, this,
intent, requestCode, options);
... 省略部分
} else {
... 省略部分
}
}
}
// ---------------------------------------------------------
// ActivityThread .java
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
// 一個應用行程只有一個
final ApplicationThread mAppThread = new ApplicationThread();
public ApplicationThread getApplicationThread()
{
return mAppThread;
}
private class ApplicationThread extends IApplicationThread.Stub {
... 省略細節
}
}
```
- ```java
// Instrumentation.java
public class Instrumentation {
public ActivityResult execStartActivity(
Context who,
IBinder contextThread, // IApplicationThread
IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
... 省略部分
try {
...省略部分
// 啟動了 ActivityTaskManager#startActivity 函數
// whoThread 就是 IApplicationThread
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
// 檢查 AMS 檢查結果
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
}
// ActivityTaskManagerService.java
// SystemService 啟動的系統進程
// IActivityTaskManager.Stub 是 Service 端的實作
public class ActivityTaskManagerService extends IActivityTaskManager.Stub { // IActivityTaskManager 是 IDE 自動生成類
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
}