ActivityManagerService
ActivityManagerService(AMS)是Android内核的三大核心功能之一,另外两个是WindowManagerService和View。ActivityManagerService它管理着四大组件,Android希望模糊进程的作用,取而代之以组件的概念,ActivityMangerService是这一理念的实现者。其次是内存管理。比如Activity退出后,其所在的进程并不会被立即杀死,从而下次在启动该Acitivity时能够提高启动速度。这些Activity只有当系统内存紧张时,才会自动被杀死,应用程序不用关心这个问题。而这些是在Ams中完成的。除此之外,同时它也管理和调度所有用户进程,它向外提供了查询系统正在运行的进程信息的API。
AMS是Binder服务,AMS从ActivityManagerNative类派生,这个类加上IactivityManager,ActivityManagerProxy和ActivityManager共同实现了AMS的Binder框架。它们的关系如图:
ActivityManagerProxy类作为ActivityManagerNative的嵌入类来实现的,它是代理对象,起接口作用。ActivityManager相当于把ActivityManagerProxy封装了起来,方便应用使用。ActivityManager通过调用ActivityManagerNative的getDefault()方法来得到ActivityManagerProxy对象的引用。
# ActivityManagerNative.java
static public IActivityManager getDefault() {
return gDefault.get();
}
gDefault的定义
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
/**
* Cast a Binder object into an activity manager interface, generating
* a proxy if needed.
*/
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ActivityManagerProxy(obj);
}
...
}
分析: gDefault是一个Singleton对象,它只会生成一个实例对象。对象的生成是通过调用ActvivityManagerNative的asInterface()方法完成的。这个方法在参数是Binder引用对象时将返回代理对象ActivityManagerProxy。
AMS的初始化:
AMS运行在SystemServer(com.android.server包下)进程中,对象的初始化是在SystemServer类初始化时完成的,如下所示:
# SystemServer.java
private SystemServiceManager mSystemServiceManager;
private ActivityManagerService mActivityManagerService;
public static void main(String[] args) {
new SystemServer().run();
}
public SystemServer() {
// Check for factory test mode.
mFactoryTestMode = FactoryTest.getMode();
}
private void run() {
.....
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
// Start services.
try {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
......
}
private void startBootstrapServices() {
...
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
....
}
分析:这里调用了mSystemServiceManager的startService()方法,这个方法中根据传入的参数:类的class来创建类的实例对象并注册到ServiceManager中。
# ActivityManagerService
// 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) {
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
//获取运行在SystemServer中的ActivityThread对象。
mSystemThread = ActivityThread.currentActivityThread();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
//创建用于处理消息的线程和Handler对象
mHandlerThread = new ServiceThread(TAG,
android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = new UiHandler();
...
//创建管理广播的数据结构
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", BROADCAST_BG_TIMEOUT, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
//创建管理组件Service的对象。
mServices = new ActiveServices(this);
//创建管理组件provider的对象
mProviderMap = new ProviderMap(this);
mAppErrors = new AppErrors(mContext, this);
// 得到系统的data和system目录
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();
//创建BatteryStatesService服务
mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().setCallback(this);
//创建ProcessStatsService服务
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
//创建AppOpsService服务
mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
...
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
//创建Intent 防火墙
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mStackSupervisor = new ActivityStackSupervisor(this);
//创建activity的管理对象
mActivityStarter = new ActivityStarter(this, mStackSupervisor);
mRecentTasks = new RecentTasks(this, mStackSupervisor);
//创建CPU使用情况的线程
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
while (true) {
...
}
}
};
//把服务加到Watchdog的监控中。
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
AMS的构造方法的作用是用来创建组件的管理对象及一些内部对象,SystemServer中创建了AMS对象以后,会调用它(AMS)的setSystemProcess()方法,如下:
#AMS
public void setSystemProcess() {
try {
//将ActivityMangerService加入到ServiceManager
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
//ProcessStates是dump进程信息的服务
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
//MemBinder是dump系统中每个进程的内存使用状况的服务
ServiceManager.addService("meminfo", new MemBinder(this));
//GraphicsBinder是dump每个进程使用图形加速卡状态的服务
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
//DbBinder是dump系统中每个进程的db状况的服务
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
//permissionController是检查Binder调用权限的服务。
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
//把SystemServer进程本身加入到process的管理中
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);
}
updateLruProcessLocked(app, false, null);
updateOomAdjLocked();
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}
分析:这个方法作用是向ServiceManager注册一些服务。注意最后一段代码它代表了SystemServer的ProcessRecord对象,并把它加入到AMS的进程(process)管理体系中。也可以说,SystemServer也可以当作framework-res.apk的应用进程,把它加入到AMS的进程(process)管理体系,对AMS而言,它对系统进程的管理就没有遗漏了。
SystemServer在启动所有服务后,将调用AMS的systemReady()方法。
# SystemServer
private void startOtherServices() {
...
// 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(new Runnable() {
@Override
public void run() {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
...
}
});
...
}
#AMS
public void systemReady(final Runnable goingCallback) {
synchronized(this) {
if (mSystemReady) {//调用时的值为false,不会执行下面的调用。
// If we're done calling all the receivers, run the next "boot phase" passed in
// by the SystemServer
if (goingCallback != null) {
goingCallback.run();
}
return;
}
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
// Make sure we have the current profile info, since it is needed for security checks.
mUserController.onSystemReady();//这里会通过UserManagerService读取系统保存的Profile信息,装载系统中已经存在的用户的profile信息。
mRecentTasks.onSystemReadyLocked();//
mAppOpsService.systemReady();
mSystemReady = true;
}
//清理进程,找到已经启动的应用进程,然后杀掉它们,目的是在启动Home前准备一个干净的环境。
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
if (!isAllowedWhileBooting(proc.info)){
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}
synchronized(this) {
if (procsToKill != null) {
for (int i=procsToKill.size()-1; i>=0; i--) {
ProcessRecord proc = procsToKill.get(i);
Slog.i(TAG, "Removing system update proc: " + proc);
removeProcessLocked(proc, true, false, "system update done");
}
}
mProcessesReady = true;
}
Slog.i(TAG, "System now ready");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
SystemClock.uptimeMillis());
//启动带有标记为FLAG_PERSISTENT的应用
synchronized(this) {
// Make sure we have no pre-ready processes sitting around.
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
ResolveInfo ri = mContext.getPackageManager()
.resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
STOCK_PM_FLAGS);
CharSequence errorMsg = null;
if (ri != null) {
ActivityInfo ai = ri.activityInfo;
ApplicationInfo app = ai.applicationInfo;
if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
mTopAction = Intent.ACTION_FACTORY_TEST;
mTopData = null;
mTopComponent = new ComponentName(app.packageName,
ai.name);
} else {
errorMsg = mContext.getResources().getText(
com.android.internal.R.string.factorytest_not_system);
}
} else {
errorMsg = mContext.getResources().getText(
com.android.internal.R.string.factorytest_no_action);
...
//读取设置信息
retrieveSettings();
final int currentUserId;
synchronized (this) {
currentUserId = mUserController.getCurrentUserIdLocked();
readGrantedUriPermissionsLocked();
}
if (goingCallback != null) goingCallback.run();
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
Integer.toString(currentUserId), currentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(currentUserId), currentUserId);
mSystemServiceManager.startUser(currentUserId);
synchronized (this) {
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
// Start up initial activity.
mBooting = true;//启动结束的标志
// Enable home activity for system user, so that the system can always boot
if (UserManager.isSplitSystemUser()) {
ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
try {
AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
UserHandle.USER_SYSTEM);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
//启动Home应用
startHomeActivityLocked(currentUserId, "systemReady");
...
long ident = Binder.clearCallingIdentity();
try {
Intent intent = new Intent(Intent.ACTION_USER_STARTED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
| Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
null, null, 0, null, null, null, AppOpsManager.OP_NONE,
null, false, false, MY_PID, Process.SYSTEM_UID,
currentUserId);
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
null, new IIntentReceiver.Stub() {
@Override
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean ordered, boolean sticky, int sendingUser)
throws RemoteException {
}
}, 0, null, null,
new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
} catch (Throwable t) {
...
} finally {
Binder.restoreCallingIdentity(ident);
}
mStackSupervisor.resumeFocusedStackTopActivityLocked();
mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
}
}
分析:这个方法是Android进入用户交互阶段最后进行的准备工作。