ActivityManagerService(AMS)--学习笔记

蜂信物联FastBee平台https://gitee.com/beecue/fastbee

阿里资料开源项目https://gitee.com/vip204888

百度低代码前端框架https://gitee.com/baidu/amis

OpenHarmony开源项目https://gitcode.com/openharmony

仓颉编程语言开放项目https://gitcode.com/Cangjie
}

… …

}

二、 通过 Lifecycle 启动初始化 AMS 系统服务

==========================================================================================

1. 静态全局 Lifecycle 类


在 AMS 中,我们看到静态全局的 final Lifecycle 类对外提供 getService()方法,方便供 SystemServer类调用。

调用方法如下:

// 通过 Lifecycle 启动 AMS 系统服务流程,详见 二

mActivityManagerService = mSystemServiceManager.startService(

ActivityManagerService.Lifecycle.class).getService();

2. AMS 继承实现关系


AMS 的继承关系如下:

public class ActivityManagerService extends IActivityManager.Stub

implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

… …

}

AMS 继承实现关系图如下:

AMS 继承实现关系图

从上图我们可以看出

1.AMS 继承IActivityManager.Stub

2.AMS 实现Watchdog.MonitorBatteryStatsImpl.BatteryCallback接口。

3.通过 Lifecycle 启动初始化 AMS 系统服务实现


AMS 是通过Lifecycle启动 AMS 并实现初始化。

具体实现代码如下:

public class ActivityManagerService extends IActivityManager.Stub

implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

… …

public static final class Lifecycle extends SystemService {

private final ActivityManagerService mService;

public Lifecycle(Context context) {

super(context);

// new ActivityManagerService 实例 见分析三

mService = new ActivityManagerService(context);

}

@Override

public void onStart() {

// 启动AMS ,见分析四

mService.start();

}

… …

public ActivityManagerService getService() {

return mService;

}

}

… …

}

三、AMS 构造函数实例实现

==========================================================================

通过 mService = new ActivityManagerService(context);,调用 AMS 构造函数,并运行在主线程中(main Thread),需要注意的是,AMS 中有多个Handler,请在loop 的时候注意,不要使用错了。

1. AMS 构造函数主要实现的功能


  1. 创建 ActivityManagerandroid.uiActivityManager:procStartActivityManager:kill服务线程。

  2. 设置前台广播、后台广播的超时时间。

  3. 设置后台Service 最大个数(8个,低 RAM 1个)

  4. 初始化 系统 Provider,以及AppErrors、AppWarnings。

  5. 创建/data/system目录,并保存procstats、appops.xml等文件。

  6. 创建 Intent 防火墙IntentFirewall,以及Activity 带来对象ActivityStartController

  7. 创建CpuTracker线程 ,收集ANRS,电池电量信息,更新CPU 状态等。

  8. 获取 Watchdog 实例,并将AMS 添加到看门狗Monitor中,以及将mHandler 添加到看门狗 线程中。

  9. 更新 oom_adj 状态。

2. AMS 构造函数实现方法


AMS 构造函数实现如下:

public ActivityManagerService(Context systemContext) {

… …

//创建名为"ActivityManager"的前台线程,并获取mHandler

// TAG 线程名,请看ActivityManagerDebugConfig,

//默认 TAG_AM 即为 ActivityManager

mHandlerThread = new ServiceThread(TAG,

THREAD_PRIORITY_FOREGROUND, false /allowIo/);

mHandlerThread.start();

mHandler = new MainHandler(mHandlerThread.getLooper());

//通过UiThread类,创建名为"android.ui"的线程

mUiHandler = mInjector.getUiHandler(this);

//创建名为"ActivityManager:procStart"的前台线程,并获取mProcStartHandler

mProcStartHandlerThread = new ServiceThread(TAG + “:procStart”,

THREAD_PRIORITY_FOREGROUND, false /* allowIo */);

mProcStartHandlerThread.start();

mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

//创建可以修改ActivityManager实例的对象

mConstants = new ActivityManagerConstants(this, mHandler);

//不重复创建 “ActivityManager:kill”后台线程,并获取sKillHandler

if (sKillHandler == null) {

sKillThread = new ServiceThread(TAG + “:kill”,

THREAD_PRIORITY_BACKGROUND, true /* allowIo */);

sKillThread.start();

sKillHandler = new KillHandler(sKillThread.getLooper());

}

//前台广播接收器,在运行超过10s将放弃执行

mFgBroadcastQueue = new BroadcastQueue(this, mHandler,

“foreground”, BROADCAST_FG_TIMEOUT, false);

//后台广播接收器,在运行超过60s将放弃执行

mBgBroadcastQueue = new BroadcastQueue(this, mHandler,

“background”, BROADCAST_BG_TIMEOUT, true);

mBroadcastQueues[0] = mFgBroadcastQueue;

mBroadcastQueues[1] = mBgBroadcastQueue;

//创建ActiveServices,其中非低内存手机后台服务最大为8个

// mMaxStartingBackground = maxBg > 0

// ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;

mServices = new ActiveServices(this);

//创建 系统 Provider

mProviderMap = new ProviderMap(this);

// 创建 Apperror 对象

mAppErrors = new AppErrors(mUiContext, this);

//创建目录/data/system

File dataDir = Environment.getDataDirectory();

File systemDir = new File(dataDir, “system”);

systemDir.mkdirs();

// 创建 管理 app Warning 的Dialog

mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler, systemDir);

//创建服务BatteryStatsService

mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);

mBatteryStatsService.getActiveStatistics().readLocked();

mBatteryStatsService.scheduleWriteToDisk();

mOnBattery = DEBUG_POWER ? true
mBatteryStatsService.getActiveStatistics().getIsOnBattery();

mBatteryStatsService.getActiveStatistics().setCallback(this);

//创建进程统计服务,信息保存在目录/data/system/procstats

mProcessStats = new ProcessStatsService(this, new File(systemDir, “procstats”));

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

mGrantFile = new AtomicFile(new File(systemDir, “urigrants.xml”), “uri-grants”);

//创建多用户、VR controller

mUserController = new UserController(this);

mVrController = new VrController(this);

… …

// 创建 Intent 防火墙

mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

mTaskChangeNotificationController =

new TaskChangeNotificationController(this, mStackSupervisor, mHandler);

// 创建控制 Activity 启动代理对象

mActivityStartController = new ActivityStartController(this);

// 创建最近任务列表,并保存在最近任务列表栈中

mRecentTasks = createRecentTasks();

mStackSupervisor.setRecentTasks(mRecentTasks);

// 创建 任务栈锁,比如在Screen pinning Mode 下

mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);

mLifecycleManager = new ClientLifecycleManager();

//创建名为"CpuTracker"的线程, 主要用于 收集 ANRS、电池状态信息等

mProcessCpuThread = new Thread(“CpuTracker”) {

@Override

public void run() {

synchronized (mProcessCpuTracker) {

mProcessCpuInitLatch.countDown();

mProcessCpuTracker.init();

}

… …

// 更新CPU 状态

updateCpuStatsNow();

… …

}

};

mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

// 获取 Watchdog看门狗实例 ,并添加到Monitor监控 以及mHandler 添加到Thread中

Watchdog.getInstance().addMonitor(this);

Watchdog.getInstance().addThread(mHandler);

// 更新 oom_adj

updateOomAdjLocked();

… …

}

3.后台Service 最大限制数设置


class ActivityManagerDebugConfig {

… …

static final boolean TAG_WITH_CLASS_NAME = false;

// Default log tag for the activity manager package.

static final String TAG_AM = “ActivityManager”;

… …

}

四、启动AMS.Start() 实现

==============================================================================

1.AMS.Start() 主要功能


  1. 移除所有的进程组

  2. 启动CpuTracker线程

  3. 启动 app 操作服务AppOpsService

  4. 将ActivityManagerInternal 添加到本地Service中

2.AMS.Start() 功能 实现


AMS.Start() 功能实现如下:

private void start() {

//移除所有的进程组

removeAllProcessGroups();

//启动CpuTracker线程

mProcessCpuThread.start();

//启动电池统计服务

mBatteryStatsService.publish();

// 启动 app 操作Service

mAppOpsService.publish(mContext);

Slog.d(“AppOps”, “AppOpsService published”);

// 将ActivityManagerInternal 添加到本地Service中

LocalServices.addService(ActivityManagerInternal.class, new LocalService());

}

五、AMS设置系统进程实现

=========================================================================

setSystemProcess 主要作用是

添加 各种服务 包括meminfo、gfxinfo、dbinfo、cpuinfo以及permissionprocessinfo系统Service。同时, 更新进程相关的 Lru 算法 ,以及oom_adj 值。

实现代码如下:

public void setSystemProcess() {

try {

//注册添加各种Service,可以使用adb shell dumpsys

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

//adb shell dumpsys meminfo 注册内存信息Service

ServiceManager.addService(“meminfo”, new MemBinder(this), /* allowIsolated= */ false,

DUMP_FLAG_PRIORITY_HIGH);

//adb shell dumpsys gfxinfo 注册GraphicsBinder

ServiceManager.addService(“gfxinfo”, new GraphicsBinder(this));

//adb shell dumpsys dbinfo 注册 DbBinder

ServiceManager.addService(“dbinfo”, new DbBinder(this));

if (MONITOR_CPU_USAGE) {

//adb shell dumpsys cpuinfo 注册CPU 信息Service

ServiceManager.addService(“cpuinfo”, new CpuBinder(this),

/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);

}

//adb shell dumpsys packages permissions 注册 系统权限 信息Service

ServiceManager.addService(“permission”, new PermissionController(this));

ServiceManager.addService(“processinfo”, new ProcessInfoService(this));

// 获取包名为 android 的应用信息,framework-res.apk

ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(

“android”, STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);

mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

synchronized (this) {

ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);

app.persistent = true;

app.pid = MY_PID;

app.maxAdj = ProcessList.SYSTEM_ADJ;

app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);

synchronized (mPidsSelfLocked) {

mPidsSelfLocked.put(app.pid, app);

}

//更新 进程 Lru 算法 ,以及oom_adj 值

updateLruProcessLocked(app, false, null);

updateOomAdjLocked();

}

}

// 当 packager manager 启动并运行时开始监听 app 操作

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

}

}

}

});

}

六、安装系统 Provider

===========================================================================

通过 SystemServer.java 类中的startOtherServices()方法mActivityManagerService.installSystemProviders();调用 AMS中的installSystemProviders方法。

下面我们看看installSystemProviders 方法的主要功能

public final void installSystemProviders() {

List providers;

synchronized (this) {

ProcessRecord app = mProcessNames.get(“system”, SYSTEM_UID);

providers = generateApplicationProvidersLocked(app);

if (providers != null) {

for (int i=providers.size()-1; i>=0; i–) {

ProviderInfo pi = (ProviderInfo)providers.get(i);

// 1&1=1 1&0=0 0&0=0

if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {

Slog.w(TAG, "Not installing system proc provider " + pi.name

  • “: not system .apk”);

//移除非系统 app

providers.remove(i);

}

}

}

}

… …

mConstants.start(mContext.getContentResolver());

// 创建 CoreSettingsObserver ,监控核心设置的变化

mCoreSettingsObserver = new CoreSettingsObserver(this);

// 创建 FontScaleSettingObserver,监控字体的变化

mFontScaleSettingObserver = new FontScaleSettingObserver();

// 创建 DevelopmentSettingsObserver 监控开发者选项

mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();

GlobalSettingsToPropertiesMapper.start(mContext.getContentResolver());

//对外公布 settings provider

RescueParty.onSettingsProviderPublished(mContext);

//mUsageStatsService.monitorPackages();

}

七、AMS.systemReady准备完成

=================================================================================

SystemServer 中的 AMS.systemReady 主要完成以下功能

  1. 确保系统Service已经准备完成。

  2. ActivityManager 引导启动完成。

  3. 开始监听NativeCrash。

  4. WebView 准备完毕,方便三方apk 调用。

  5. 启动车载相关的服务。

  6. 启动SystemUI。

  7. 确保 MakeNetworkManagementService 准备完成。

  8. 启动 Watchdog 看门狗程序。

  9. 等待所有的app数据预加载,然后,可以启动三方app。

  10. Location、telephony、输入法、Media、MMS、Daemon等相关的Service已经运行并准备好

SystemServer中具体实现代码情况下文:

public final class SystemServer {

… …

/**

  • The main entry point from zygote.

*/

public static void main(String[] args) {

new SystemServer().run();

}

public SystemServer() {

… …

}

private void run() {

… …

//启动系统服务

startOtherServices();

… …

}

private void startOtherServices() {

… …

// 系统准备完毕,可以让第三代码调用

mActivityManagerService.systemReady(() -> {

Slog.i(TAG, “Making services ready”);

traceBeginAndSlog(“StartActivityManagerReadyPhase”);

// ActivityManager 准备完毕

mSystemServiceManager.startBootPhase(

SystemService.PHASE_ACTIVITY_MANAGER_READY);

traceEnd();

traceBeginAndSlog(“StartObservingNativeCrashes”);

try {

// 开始监听 Native Crash

mActivityManagerService.startObservingNativeCrashes();

} catch (Throwable e) {

reportWtf(“observing native crashes”, e);

}

traceEnd();

//WebView 准备好,方便三方apk 调用

final String WEBVIEW_PREPARATION = “WebViewFactoryPreparation”;

Future<?> webviewPrep = null;

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

}

// 启动SystemUI

traceBeginAndSlog(“StartSystemUI”);

try {

startSystemUi(context, windowManagerF);

} catch (Throwable e) {

reportWtf(“starting System UI”, e);

}

traceEnd();

// MakeNetworkManagementService 准备完成

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

}

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

// 启动 Watchdog 看门狗程序

traceBeginAndSlog(“StartWatchdog”);

Watchdog.getInstance().start();

traceEnd();

//等待所有的app数据预加载

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

}

// 三方 app 已准备好,可以启动

mSystemServiceManager.startBootPhase(

SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

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(“MakeCommonTimeManagementServiceReady”);

try {

if (commonTimeMgmtServiceF != null) {

commonTimeMgmtServiceF.systemRunning();

}

} catch (Throwable e) {

reportWtf(“Notifying CommonTimeManagementService running”, e);

}

traceEnd();

traceBeginAndSlog(“MakeInputManagerServiceReady”);

try {

// 输入法相关的Service已经运行并准备好

// TODO(BT) Pass parameter to input manager

if (inputManagerF != null) inputManagerF.systemRunning();

} catch (Throwable e) {

reportWtf(“Notifying InputManagerService running”, e);

}

traceEnd();

traceBeginAndSlog(“MakeTelephonyRegistryReady”);

try {

// telephony相关的Service已经运行并准备好

if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2021最新上万页的大厂面试真题

七大模块学习资料:如NDK模块开发、Android框架体系架构…

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
**第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。
**第二,**开发几年,不知道如何进阶更进一步,比较迷茫。
第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢!
由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示

ng();

}

} catch (Throwable e) {

reportWtf(“Notifying CommonTimeManagementService running”, e);

}

traceEnd();

traceBeginAndSlog(“MakeInputManagerServiceReady”);

try {

// 输入法相关的Service已经运行并准备好

// TODO(BT) Pass parameter to input manager

if (inputManagerF != null) inputManagerF.systemRunning();

} catch (Throwable e) {

reportWtf(“Notifying InputManagerService running”, e);

}

traceEnd();

traceBeginAndSlog(“MakeTelephonyRegistryReady”);

try {

// telephony相关的Service已经运行并准备好

if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2021最新上万页的大厂面试真题

[外链图片转存中…(img-mFW8M3p8-1725164458107)]

七大模块学习资料:如NDK模块开发、Android框架体系架构…

[外链图片转存中…(img-64o82RvA-1725164458108)]

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
**第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。
**第二,**开发几年,不知道如何进阶更进一步,比较迷茫。
第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢!
由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值