自从读过Android内核剖析这本书之后,对整个安卓的系统有了更深的认识和理解,前面写了3篇文章(深入PMS源码)分析了PMS的相关代码,之后会将相关知识都整理在博客上,本篇开始将从源码角度分析AMS的执行逻辑,AMS作为Android的核心服务,了解其内部流程会让开发者对程序的执行有更深刻的认识,主要的流程逻辑放在下一篇中分析,这里先分析下基础部分便于更好的理解之后的内容;
AMS作为系统的主要服务,也是在Android系统启动后由系统来启动,由Android系统启动过程知道系统启动服务通过SystemServer完成,在SystemServer中调用startBootstrapServices()启动核心服务,AMS也是在此方法中完成启动
private void startBootstrapServices() {
559 mActivityManagerService = mSystemServiceManager.startService(
560 ActivityManagerService.Lifecycle.class).getService(); //1、使用SystemServiceManager创建AMS对象
561 mActivityManagerService.setSystemServiceManager(mSystemServiceManager); //赋值AMS中mSystemServiceManager
562 mActivityManagerService.setInstaller(installer); //赋值AMS中的installer
}
上面的代码也是在Android系统启动过程中出现过的,使用SystemServiceManager.startService()方法,传入ActivityManagerService.Lifecycle.class启动服务,由前面的学习知道startService()方法中会创建Lifecycle对象,并调用onStart()方法
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context); // 1、创建AMS对象
}
@Override
public void onStart() {
mService.start(); // 2、执行start()方法
}
public ActivityManagerService getService() { // 3、返回AMS对象
return mService;
}
}
在Lifecycle的构造函数中直接创建ActivityManagerService对象,然后调用ActivityManagerService.start()方法
public ActivityManagerService(Context systemContext) {
mSystemThread = ActivityThread.currentActivityThread(); // 1、获取ActivityThread实例
mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper()); // 2、使用HandlerThread初始化一个线程和Handler对象
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart”, // 3、初始化用于进程启动的ProcStartHandle对象
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
if (sKillHandler == null) {
sKillThread = new ServiceThread(TAG + ":kill",
THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
sKillThread.start();
sKillHandler = new KillHandler(sKillThread.getLooper()); // 4、初始化用于杀死进程的sKillHandler对象
}
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this); // 初始化属性
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system”); // 创建/system/文件夹
systemDir.mkdirs();
mLifecycleManager = new ClientLifecycleManager();//初始化ClientLifecycleManager对象
mProcessCpuThread = new Thread("CpuTracker") {。。。。。。} // 创建mProcessCpuThread线程
}
在实例化ActivityManagerService对象时,主要执行以下操作:
private void start() {
mProcessCpuThread.start(); // 1、
mBatteryStatsService.publish();
mAppOpsService.publish(mContext); //
LocalServices.addService(ActivityManagerInternal.class, new LocalService()); // 2、
try {
mProcessCpuInitLatch.await(); //3、
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
在start()方法中,首先启动mProcessCpuThread线程,使用LocalServices注册ActivityManagerInternal类型的LocalService对象,关于LocalServices它功能类似于ServiceManager,在内部使用静态变量保存注册的Class和对象的关系,在使用时直接获取使用,不过它只能在相同线程中使用,最后调用使用CountDownLatch同步线程,等待mProcessCpuThread线程启动完成;
第二个部分主要介绍AMS是如何管理生命周期,如何回调生命周期方法的,在Android内核剖析书中主要针对Android 2.3版本,从其源码中可以看出,当时的AMS中功能是十分臃肿的,而且对生命周期的回调也是直接调用的,代码从理解上来说会不较容易,笔者在看完Android 2.3源码后又学习的Android P的源码,在Android P中将对生命周期的管理单独抽取封装成模块,本片文章就看下Android P中的源码,在AndroidP中执行程序的onPause()方法的过程被封装成
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
使用模版模式,将所有对生命周期的回调都封装成统一的样式,通过创建不同的对象达到不同的效果,在介绍上述代码执行前先介绍下主要的几个类;
public abstract class ActivityLifecycleItem extends ClientTransactionItem {
@IntDef(prefix = { "UNDEFINED", "PRE_", "ON_" }, value = {
UNDEFINED,
PRE_ON_CREATE,
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_RESTART
})
@Retention(RetentionPolicy.SOURCE)
public @interface LifecycleState{} // 定义了生命周期状态的注解
public static final int UNDEFINED = -1;
public static final int PRE_ON_CREATE = 0;
public static final int ON_CREATE = 1;
public static final int ON_START = 2;
public static final int ON_RESUME = 3;
public static final int ON_PAUSE = 4;
public static final int ON_STOP = 5;
public static final int ON_DESTROY = 6;
public static final int ON_RESTART = 7;
@LifecycleState
public abstract int getTargetState(); // 返回相应的状态
@Override
public void recycle() { // 生命空的recycle()方法
}
}
在Android系统中将每个生命周期都抽象成单独的Item,然后创建抽象的ActivityLifecycleItem类,在其中声明方法周期注解、抽象方法和对应的常量,另外ActivityLifecycleItem继承了ClientTransactionItem类,如果说ActivityLifecycleItem类是统一所有生命周期Item的Base类,那ClientTransactionItem就是定义了如何使用每个Item 的框架类;
public class ClientTransaction implements Parcelable, ObjectPoolItem {
private List<ClientTransactionItem> mActivityCallbacks;
private ActivityLifecycleItem mLifecycleStateRequest; // 要执行的lifecycle
private IApplicationThread mClient; // 发起请求的Client
private IBinder mActivityToken;
// 1、获取ClientTransaction对象
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
if (instance == null) {
instance = new ClientTransaction();
}
instance.mClient = client;
instance.mActivityToken = activityToken;
return instance;
}
public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
mLifecycleStateRequest = stateRequest; // 2、设置执行生命周期对应的 Item
}
// 3、执行ClientTransaction对象的方法
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this); //
}
}
@Override
public void recycle() { //4、
if (mActivityCallbacks != null) {
int size = mActivityCallbacks.size();
for (int i = 0; i < size; i++) {
mActivityCallbacks.get(i).recycle();
}
mActivityCallbacks.clear();
}
if (mLifecycleStateRequest != null) {
mLifecycleStateRequest.recycle();
mLifecycleStateRequest = null;
}
mClient = null;
mActivityToken = null;
ObjectPool.recycle(this);
}
上述代码为ClientTransaction中主要的功能部分:
上面的执行过程中除了创建对象、设置请求Request、回收对象真正执行任务是在Client中,这里的Client是ApplicaitonThread对象中方法
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this); // 1、执行preExecute()
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); //2、发送事件执行transaction,在ActivityThread中
}
在scheduleTransaction()方法中首先调用transaction.preExecute()方法,preExecute会回调每个Item.preExecute(),主要做执行前的准备工作,然后调用sendMessage()发送时间消息,处理事件是在ActivityThread中
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction) ; // 调用TransactionExecutor执行transaction对象
if (isSystem()) {
transaction.recycle(); // 释放、回收资源
}
break;
在获取到消息事件中的ClientTransaction对象后,调用TransactionExecutor中方法执行transaction对象,在execute()方法中会调用executeLifecycleState()
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); // 1、获取传入的LifecycleItem
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token); // 2、获取要执行的ActivityRecord
if (r == null) {
return;
}
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
lifecycleItem.execute(mTransactionHandler, token, mPendingActions); // 3、执行LifecycleItem的execute()
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); // 4、执行postExecute()回调通知执行结果
}
在executeLifecycleState()中首先获取要执行的Request,其实获取的就是要执行的生命周期的Item,然后执行Item的execute()和postExecute()方法,execute主要执行任务而postExecute在执行任务结束后回到结果,下面以Activity的onPause为例
public class PauseActivityItem extends ActivityLifecycleItem { //
private boolean mFinished;
private boolean mUserLeaving;
private int mConfigChanges;
private boolean mDontReport;
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM”); // 1、
}
@Override
public int getTargetState() {
return ON_PAUSE;
}
@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
if (mDontReport) {
return;
}
try {
ActivityManager.getService().activityPaused(token); // 2
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
private PauseActivityItem() {}
public static PauseActivityItem obtain(boolean finished, boolean userLeaving, int configChanges,
boolean dontReport) {
PauseActivityItem instance = ObjectPool.obtain(PauseActivityItem.class);//使用对象池复用对象
if (instance == null) {
instance = new PauseActivityItem();
}
instance.mFinished = finished;
instance.mUserLeaving = userLeaving;
instance.mConfigChanges = configChanges;
instance.mDontReport = dontReport;
return instance;
}
@Override
public void recycle() {
super.recycle();
mFinished = false;
mUserLeaving = false;
mConfigChanges = 0;
mDontReport = false;
ObjectPool.recycle(this); // 回收对象
}
}
在PauseItem中主要执行以下逻辑:
1、生命周期回调框架会调用其execute(),在execute()中调用I ApplicationThread.handlePauseActivity()方法,处理方法暂停
2、在执行完Activity的pause之后会调用postExecute(),在postExecute中回调通知AMS.activityPaused(),通知AMS方法暂停完成;
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
现在来解释下开始时给出的代码,使用的执行架构就是上面分析的内容,那getLifecycleManager()获取的是什么呢?获取的其实是ClientLifecycleManager对象,就是AMS在构造函数中初始化的,ClientLifecycleManager的作用封装了ClientTransaction
对象的创建、设置请求Request、schedule()执行、recycle()回收部分;
class ClientLifecycleManager {
// 使用此方法可以实现回调生命周期中的方法
void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
@NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
final ClientTransaction clientTransaction = transactionWithState(client, activityToken,stateRequest);
scheduleTransaction(clientTransaction);
}
//根据请求的参数,封装ClientTransaction对象
private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,
@NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) {
final ClientTransaction clientTransaction = ClientTransaction.obtain(client, activityToken);
clientTransaction.setLifecycleStateRequest(stateRequest);
return clientTransaction;
}
// 执行具体的ClientTransaction对象
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule(); // 调用schedule()
if (!(client instanceof Binder)) {
transaction.recycle();//调用recycle()
}
}
}
在调用scheduleTransaction()传入参数后,首先调用transactionWithState()使用参数创建ClientTransaction对象,然后调用scheduleTransaction(),在scheduleTransaction中触发schedule的执行,然后系统就会执行相应的Item,在执行结束后调用recycle()回收对象;
上面就是AMS中数据结构和两个基础模块的分析,下一篇文章将带着这些基础去分析AMS如何管理和调度Activity的。