開始進入Framework的源碼分析觉吭,在分析源碼之前趁冈,先來了解一下android系統(tǒng)啟動的流程唯咬,如下圖所示:
AMS介紹
AMS(Activity Manager Service)是android系統(tǒng)中非常重要的一個系統(tǒng)服務渐夸,他主要負責四大組件的啟動,切換,調度以及應用進程的管理和調度工作财破。
也就說所有的app應用都會和AMS打交道溢吻。
AMS作為系統(tǒng)的引導服務,是在SystemServer進程中啟動SystemServer時創(chuàng)建并啟動的怔毛,關于SystemServer的啟動流程另外分析员萍。
AMS繼承自IActivityManager.Stub ,作為系統(tǒng)服務的服務者提供系統(tǒng)服務。
AMS啟動源碼分析
先來看看下面這張思維導圖拣度,方便在看到源碼分析時更清晰:
1碎绎、創(chuàng)建AMS對象,并啟動AMS
1.1抗果、獲取ActivityTaskManagerService服務:
//SystemServer.java
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
}
進入SystemServiceManager的startService()方法中筋帖,這里傳遞的參數是ActivityTaskManagerService.Lifecycle.class
注意:因為startService()執(zhí)行的結果還需要調用getService()方法,所以startService()是帶了返回值
//SystemServiceManager.java
public SystemService startService(String className) {
//通過類加載器加載service
final Class<SystemService> serviceClass = loadClassFromLoader(className,
this.getClass().getClassLoader());
return startService(serviceClass);//此處進入startService()方法
}
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)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
//通過類的構造器來創(chuàng)建service實例
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
startService(service);
return service;//這里返回的service是 ActivityTaskManagerService.Lifecycle對象
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
由上面的源碼知道是通過反射來調用構造器創(chuàng)建的對象冤馏,而需要創(chuàng)建的對象是ActivityTaskManagerService.Lifecycle日麸,那么接下來就進入ActivityTaskManagerService靜態(tài)內部類Lifecycle的構造方法執(zhí)行:
//ActivityTaskManagerService.java
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
//這里就創(chuàng)建好了ActivityTaskManagerService對象
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
//這里就是上一步調回進來的地方
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
@Override
public void onUnlockUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.onUserUnlocked(userId);
}
}
@Override
public void onCleanupUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
}
}
public ActivityTaskManagerService getService() {
return mService;
}
}
ActivityTaskManagerService.Lifecycle對象創(chuàng)建時已經將ActivityTaskManagerService對象也創(chuàng)建好了,但是返回的是ActivityTaskManagerService.Lifecycle的對象實例逮光,需要調用ActivityTaskManagerService.Lifecycle類的getServices()方法來得到ActivityTaskManagerService對象實例赘淮。
1.2、創(chuàng)建AMS對象
回到SystemServer的啟動引導服務方法中:
//SystemServer.java
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
//這一步已經完成
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//從這里開始分析
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
}
下面從ActivityManagerService類的內部靜態(tài)Lifecycle的靜態(tài)方法startService()開始分析:
這里和上一步的ActivityTaskManagerService的內部靜態(tài)類Lifecycle要區(qū)分一下睦霎,
//ActivityManagerService.java
public static final class Lifecycle extends SystemService {
//這里就是SystemService中調用的startService(),該方法直接返回的是AMS對象
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
//下面是調用了SystemServiceManager的帶有返回值的startService(),
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
}
進入SystemServiceManager的startService()方法梢卸,傳入的參數是:ActivityManagerService.Lifecycle.class
這里和上一步ActivityTaskManagerService.Lifecycle步驟一致:
//SystemServiceManager.java
public SystemService startService(String className) {
//通過類加載器加載service
final Class<SystemService> serviceClass = loadClassFromLoader(className,
this.getClass().getClassLoader());
return startService(serviceClass);//此處進入startService()方法
}
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)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
//通過類的構造器來創(chuàng)建service實例
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
startService(service);
return service;//這里返回的service是 ActivityTaskManagerService.Lifecycle對象
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
這里就直接進入到ActivityManagerService.Lifecycle類的構造方法,在構造方法中創(chuàng)建AMS對象副女,通過getService()來獲取AMS對象蛤高,至此AMS對象就創(chuàng)建好了。
//ActivityManagerService.java
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
//在構造方法中創(chuàng)建了AMS對象
mService = new ActivityManagerService(context, sAtm);
}
//這里就是SystemService中調用的startService(),該方法直接返回的是AMS對象
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
//下面是調用了SystemServiceManager的帶有返回值的startService(),
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
mService.start();
}
@Override
public void onBootPhase(int phase) {
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
} else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
mService.startBroadcastObservers();
} else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
mService.mPackageWatchdog.onPackagesReady();
}
}
@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}
public ActivityManagerService getService() {
return mService;
}
}
1.3、啟動AMS
關于AMS的啟動戴陡,其實細心的同學已經注意到了塞绿,就是在ActivityManagerService.Lifecycle對象創(chuàng)建成功(在SystemServiceManager中創(chuàng)建)且在返回對象之前會調用一次不帶返回值的startService(),
//SystemServiceManager.java
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)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
//通過類的構造器來創(chuàng)建service實例
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
//下面啟動ActivityServiceManager.Lifecycle服務
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
//SystemServiceManager.java
//注意這里傳遞進來的service是ActivityServiceManager.Lifecycle對象
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
//這里會調到ActivityServiceManager.Lifecycle對的onStart()方法
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
接下來又回到ActivityServiceManager.Lifecycle中:
//ActivityServiceManager.java
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context, sAtm);
}
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
//這里會調用AMS的onstart方法
mService.start();
}
@Override
public void onBootPhase(int phase) {
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
} else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
mService.startBroadcastObservers();
} else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
mService.mPackageWatchdog.onPackagesReady();
}
}
@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}
public ActivityManagerService getService() {
return mService;
}
}
進入AMS的start()方法
//ActivityManagerService.java
private void start() {
removeAllProcessGroups();
mProcessCpuThread.start();
mBatteryStatsService.publish();
mAppOpsService.publish();
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, mInternal);
mActivityTaskManager.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
// Wait for the synchronized block started in mProcessCpuThread,
// so that any other access to mProcessCpuTracker from main thread
// will be blocked during mProcessCpuTracker initialization.
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
至此就是全部AMS的啟動流程結束。
2恤批、加入SystemServiceManager异吻、添加安裝器installer
//SystemServer.java
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
//這一步已經完成
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//AMS對象已經創(chuàng)建成功并啟動
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
//來看看下面的
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
}
2.1、SystemServiceManager負責管理system service的創(chuàng)建喜庞、啟動等生命周期事件
說明:
- 使用ArrayList來存放系統(tǒng)Service的對象
- 使用ArrayMap存放每一個service類的路徑和對應的類加載器
- 通過類加載器加載類诀浪,然后通過反射來調用類的構造函數創(chuàng)建對象
public class SystemServiceManager {
private static final String TAG = "SystemServiceManager";
//............
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
// Map of paths to PathClassLoader, so we don't load the same path multiple times.
private final ArrayMap<String, PathClassLoader> mLoadedPaths = new ArrayMap<>();
private int mCurrentPhase = -1;
private UserManagerInternal mUserManagerInternal;
SystemServiceManager(Context context) {
mContext = context;
}
/**
* Starts a service by class name.
*
* @return The service instance.
*/
public SystemService startService(String className) {
final Class<SystemService> serviceClass = loadClassFromLoader(className,
this.getClass().getClassLoader());
return startService(serviceClass);
}
/**
* Starts a service by class name and a path that specifies the jar where the service lives.
*
* @return The service instance.
*/
public SystemService startServiceFromJar(String className, String path) {
PathClassLoader pathClassLoader = mLoadedPaths.get(path);
if (pathClassLoader == null) {
// NB: the parent class loader should always be the system server class loader.
// Changing it has implications that require discussion with the mainline team.
pathClassLoader = new PathClassLoader(path, this.getClass().getClassLoader());
mLoadedPaths.put(path, pathClassLoader);
}
final Class<SystemService> serviceClass = loadClassFromLoader(className, pathClassLoader);
return startService(serviceClass);
}
/*
* Loads and initializes a class from the given classLoader. Returns the class.
*/
@SuppressWarnings("unchecked")
private static Class<SystemService> loadClassFromLoader(String className,
ClassLoader classLoader) {
try {
return (Class<SystemService>) Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException("Failed to create service " + className
+ " from class loader " + classLoader.toString() + ": 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. Also ensure that the correct path for the "
+ "classloader is supplied, if applicable.", ex);
}
}
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
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)) {
throw new 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) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
//.....此處省略了更多代碼
}
2.2、Installer一個安裝應用的安裝器
責任:負責應用數據的create延都、restore雷猪、migrate、clear晰房、destory求摇、fixup、move等管理
原理:獲取installd的Binder服務端代理對象來完成相關的操作殊者;
public class Installer extends SystemService {
public Installer(Context context) {
this(context, false);
}
/**
* @param isolated indicates if this object should <em>not</em> connect to
* the real {@code installd}. All remote calls will be ignored
* unless you extend this class and intercept them.
*/
public Installer(Context context, boolean isolated) {
super(context);
mIsolated = isolated;
}
/**
* Yell loudly if someone tries making future calls while holding a lock on
* the given object.
*/
public void setWarnIfHeld(Object warnIfHeld) {
mWarnIfHeld = warnIfHeld;
}
@Override
public void onStart() {
if (mIsolated) {
mInstalld = null;
} else {
connect();
}
}
private void connect() {
IBinder binder = ServiceManager.getService("installd");
if (binder != null) {
try {
binder.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
Slog.w(TAG, "installd died; reconnecting");
connect();
}
}, 0);
} catch (RemoteException e) {
binder = null;
}
}
if (binder != null) {
mInstalld = IInstalld.Stub.asInterface(binder);
try {
invalidateMounts();
} catch (InstallerException ignored) {
}
} else {
Slog.w(TAG, "installd not found; trying again");
BackgroundThread.getHandler().postDelayed(() -> {
connect();
}, DateUtils.SECOND_IN_MILLIS);
}
}
/**
* Do several pre-flight checks before making a remote call.
*
* @return if the remote call should continue.
*/
private boolean checkBeforeRemote() {
if (mWarnIfHeld != null && Thread.holdsLock(mWarnIfHeld)) {
Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() + " is holding 0x"
+ Integer.toHexString(System.identityHashCode(mWarnIfHeld)), new Throwable());
}
if (mIsolated) {
Slog.i(TAG, "Ignoring request because this installer is isolated");
return false;
} else {
return true;
}
}
public long createAppData(String uuid, String packageName, int userId, int flags, int appId,
String seInfo, int targetSdkVersion) throws InstallerException {
if (!checkBeforeRemote()) return -1;
try {
return mInstalld.createAppData(uuid, packageName, userId, flags, appId, seInfo,
targetSdkVersion);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
/**
* Batched version of createAppData for use with multiple packages.
*/
public void createAppDataBatched(String[] uuids, String[] packageNames, int userId, int flags,
int[] appIds, String[] seInfos, int[] targetSdkVersions) throws InstallerException {
if (!checkBeforeRemote()) return;
final int batchSize = 256;
for (int i = 0; i < uuids.length; i += batchSize) {
int to = i + batchSize;
if (to > uuids.length) {
to = uuids.length;
}
try {
mInstalld.createAppDataBatched(Arrays.copyOfRange(uuids, i, to),
Arrays.copyOfRange(packageNames, i, to), userId, flags,
Arrays.copyOfRange(appIds, i, to), Arrays.copyOfRange(seInfos, i, to),
Arrays.copyOfRange(targetSdkVersions, i, to));
} catch (Exception e) {
throw InstallerException.from(e);
}
}
}
public void restoreconAppData(String uuid, String packageName, int userId, int flags, int appId,
String seInfo) throws InstallerException {
if (!checkBeforeRemote()) return;
try {
mInstalld.restoreconAppData(uuid, packageName, userId, flags, appId, seInfo);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
public void migrateAppData(String uuid, String packageName, int userId, int flags)
throws InstallerException {
if (!checkBeforeRemote()) return;
try {
mInstalld.migrateAppData(uuid, packageName, userId, flags);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
public void clearAppData(String uuid, String packageName, int userId, int flags,
long ceDataInode) throws InstallerException {
if (!checkBeforeRemote()) return;
try {
mInstalld.clearAppData(uuid, packageName, userId, flags, ceDataInode);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
public void destroyAppData(String uuid, String packageName, int userId, int flags,
long ceDataInode) throws InstallerException {
if (!checkBeforeRemote()) return;
try {
mInstalld.destroyAppData(uuid, packageName, userId, flags, ceDataInode);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
public void fixupAppData(String uuid, int flags) throws InstallerException {
if (!checkBeforeRemote()) return;
try {
mInstalld.fixupAppData(uuid, flags);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
public void moveCompleteApp(String fromUuid, String toUuid, String packageName,
int appId, String seInfo, int targetSdkVersion,
String fromCodePath) throws InstallerException {
if (!checkBeforeRemote()) return;
try {
mInstalld.moveCompleteApp(fromUuid, toUuid, packageName, appId, seInfo,
targetSdkVersion, fromCodePath);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
}
總結:
1与境、通過反射來創(chuàng)建service的靜態(tài)內部類Lifecycle的對象,在其構造方法中創(chuàng)建ATMS 猖吴,AMS對象摔刁;
2、創(chuàng)建后ATMS ,AMS對象后距误,調用SystemServer的startService()方法簸搞,調用Lifecycle的onStart()方法,在其中執(zhí)行對應的ATMS ,AMS對象的start()方法啟動服務
3准潭、通過Lifecycle對象的getService()來獲取ATMS ,AMS對象趁俊,然后進行對象的配置:加入SystemServerManager中,添加Installer安裝器等