AMS是Android操作系统中的一个核心组件,它的全称:Activity Manager Service,但它不仅管理Activity,更是Android应用程序的管理器。负责管理应用的生命周期、任务栈(Android12后委托给ATMS管理)、进程和活动之间的切换等。
由于AMS的代码量十分庞大,需要有针对性的研究才不会陷入源码的海洋无法自拔。本文将结合源码对AMS的进程管理展开分析。本文基于Android12分析,以前的版本的源码略有差异,比如进程管理优先级的代码,12以前是放到AMS中,12之后,主要委托到了ProcessList类中,但核心思想和算法没有改变。
核心思想
对队列中的进程进行调整,根据hasActivity,hasService条件,将整个队列划分为三个区域。最后根据LRU算法,对进程所在的区域中调整位置。

分析过程已经贴在代码注释中。
ps:由于分析是本人的理解,难免有误差,所以会保存源码中的英文注释。
核心代码
final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
ProcessRecord client) {
final boolean hasActivity = app.hasActivitiesOrRecentTasks() || app.hasClientActivities()
|| app.treatLikeActivity;
final boolean hasService = false; // not impl yet. app.services.size() > 0;
if (!activityChange && hasActivity) {
// The process has activities, so we are only allowing activity-based adjustments
// to move it. It should be kept in the front of the list with other
// processes that have activities, and we don't want those to change their
// order except due to activity operations.
//进程中的activity没有改变,就不需要调整
return;
}
//id自增,保证唯一性
mLruSeq++;
final long now = SystemClock.uptimeMillis();
//保存更新调整后的时间
app.lastActivityTime = now;
// First a quick reject: if the app is already at the position we will
// put it, then there is nothing to do.
//快速校验,如果当前有包含act

最低0.47元/天 解锁文章
352

被折叠的 条评论
为什么被折叠?



