您的位置:首页 > 移动开发 > Android开发

ams功能分析之activity启动过程

2017-11-28 09:26 435 查看
以点击桌面图标启动为例;

前提知识:

桌面也是activity,即Launcher继承Activity

APP进程

Launcher源码摘取分析:

public void onClick(View v) {
...
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {

//点击的view必须设置tag为 ShortcutInfo类型,调用
onClickAppShortcut(v);

} else if (tag instanceof FolderInfo) {

//点击文件夹
if (v instanceof FolderIcon) {
onClickFolderIcon(v);
}

} else if ((FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP && v instanceof PageIndicator) ||
(v == mAllAppsButton && mAllAppsButton != null)) {

//点击进入grid列表式,老版手机的菜单界面
onClickAllAppsButton(v);

} else if (tag instanceof AppInfo) {

//通过点击事件调用, 点击的view必须设置tag为AppInfo
startAppShortcutOrInfoActivity(v);

} else if (tag instanceof LauncherAppWidgetInfo) {

//点击窗口小部件,时钟日历等
if (v instanceof PendingAppWidgetHostView) {
onClickPendingWidget((PendingAppWidgetHostView) v);
}
}
}

//其他点击不分析
protected void onClickAppShortcut(final View v) {
...
startAppShortcutOrInfoActivity(v);
}

private void startAppShortcutOrInfoActivity(View v) {

ItemInfo item = (ItemInfo) v.getTag();
Intent intent = item.getIntent();
if (intent == null) {
throw new IllegalArgumentException("Input must have a valid intent");
}

//启动应用最终都会调到该方法
boolean success = startActivitySafely(v, intent, item);
}


*通过参数分析功能:多了intent 和 ItemInfo参数,证明Launch界面的方法的作用是取到了点击view图标对应的应用的信息数据,传递给AMS操作(可以想象的到,自己写一些简单的模拟launch的时候是这样干的)

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mApps = getPackageManager().queryIntentActivities(mainIntent, 0);//获取全部应用,具体分析PMS时候在研究
ResolveInfo info = mApps.get(position);
String pkg = info.activityInfo.packageName;//包名
String cls = info.activityInfo.name;//应用launch界面名
ComponentName componet = new ComponentName(pkg, cls);//包名和类名拼接处理的封装类
Intent i = new Intent();
i.setComponent(componet);
startActivity(i);//启动对应包类名信息的(主)界面


*

public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {

//切换动画
boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
Bundle optsBundle = useLaunchAnimation ? getActivityLaunchOptions(v) : null;
UserHandle user = item == null ? null : item.user;
判断...
//在新栈内启动
/**
* 为什么要在新建的栈内启动?因为当前的launcher界面是系统桌面,AS堆信息id为0,栈信息id为,小于1000,在ASS管理中应属于mHome中
* 而新启动的界面是应用界面,应该放到非系统管理集合中
* Stack #0:   Task id #1
*/
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//调用activity的startActivity()
startActivity(intent, optsBundle);
}


*通过参数分析功能:少了item,多了optsBundle。item在方法中做了判断,判断是否是快捷入口然后进行一些其他的判断(不懂,暂时跳过把),bundle就是动画id等数据

额外补充方法说明:

//1.optsBundle为啥是界面切换动画
@TargetApi(Build.VERSION_CODES.M)
public Bundle getActivityLaunchOptions(View v) {
//版本判断
if (Utilities.ATLEAST_MARSHMALLOW) {
int left = 0, top = 0;
int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
if (v instanceof TextView) {
Drawable icon = Workspace.getTextViewIcon((TextView) v);
if (icon != null) {
Rect bounds = icon.getBounds();
left = (width - bounds.width()) / 2;
top = v.getPaddingTop();
width = bounds.width();
height = bounds.height();
}
}
return ActivityOptions.makeClipRevealAnimation(v, left, top, width, height).toBundle();  //切剪动画啥的
} else if (Utilities.ATLEAST_LOLLIPOP_MR1) {
return ActivityOptions.makeCustomAnimation(
this, R.anim.task_open_enter, R.anim.no_anim).toBundle();      //进出动画
//ActivityOptions和bundle没有关系,注意有个.toBundle方法。。。。。
}
return null;
}

public static ActivityOptions makeClipRevealAnimation(View source,
int startX, int startY, int width, int height) {
ActivityOptions opts = new ActivityOptions();
opts.mAnimationType = ANIM_CLIP_REVEAL;
int[] pts = new int[2];
source.getLocationOnScreen(pts);
opts.mStartX = pts[0] + startX;
opts.mStartY = pts[1] + startY;
opts.mWidth = width;
opts.mHeight = height;
return opts;
}

public static ActivityOptions makeCustomAnimation(Context context,
int enterResId, int exitResId, Handler handler, OnAnimationStartedListener listener) {
ActivityOptions opts = new ActivityOptions();
opts.mPackageName = context.getPackageName();
opts.mAnimationType = ANIM_CUSTOM;
opts.mCustomEnterResId = enterResId;
opts.mCustomExitResId = exitResId;
opts.setOnAnimationStartedListener(handler, listener);
return opts;
}

//最终把包括切换动画的资源id在内的信息封装进了Bundle
//A mapping from String keys to various {@link Parcelable} values.
//Bundle是一个序列化的map封装工具类,提供了一些方便使用的方法,如put,get等
//mMap = capacity > 0 ? new ArrayMap<String, Object>(capacity) : new ArrayMap<String, Object>(); BaseBundle构造时创建


*

Activity源码摘取分析:

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}

//重载最终调用到
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {

// Activity mParent; attach()方法中进行的赋值方法
/**
*
* attach()在ActivityThread的方法performLaunchActivity方法中被调用,该方法是启动新的activity的必经方法,确切的说是启动oncreate的方法,
* 而mParent = r.parent,r是ams机制中的activityRecord在应用层的实体
*/
if (mParent == null) {
options = transferSpringboardActivityOptions(options);

//执行启动
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(this,
//重要参数, Binder (ApplicationThread extends IApplicationThread.Stub), 用作ams进程和应用进程之间通讯
mMainThread.getApplicationThread(),
//重要参数, Binder attach()方法中进行的赋值(界面创建时由AMS创建token,作为界面的标识,传给客户端进程,用于ams和指定的该activity交互的标识依据)
mToken,
this,
intent,
requestCode,
options);
if (ar != null) {
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
}
if (requestCode >= 0) {
//带返回
mStartedActivity = true;
}

} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}


*通过参数分析功能:

mInstrumentation.execStartActivity(thi
4000
s, context

mMainThread.getApplicationThread(), ams和app之间通讯的binder mMainThread,在attach中赋值

mToken, ams和app和wms判定同一个界面的标识 mToken,在attach中赋值

this, target

intent, 要启动的界面的信息封装(包名,主界面class名,flag等)

requestCode, 是否要带回数据的请求标识code(startActivityForResult, setResult)

options 切换动画等资源id封装

);

带着当前界面的信息,要启动的界面的信息,进行启动请求*

Instrumentation源码摘取分析:

public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
int result = ActivityManager.getService()   //binder通讯,代理ams调用接口
.startActivity(
whoThread,
who.getBasePackageName(),
intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token,
target,
requestCode,
0,
null,
options);
}


*通过参数分析功能:

int result = ActivityManager.getService()

.startActivity(

whoThread, ams和app之间通讯的binde

who.getBasePackageName(), 上下文获取包名

intent, 数据

intent.resolveTypeIfNeeded(who.getContentResolver()), 解析intent数据使用,可能是解码方式,注解提示不重要

token, 标识(当前launch界面)

target, target

requestCode, 请求code

0, startFlags本以为是启动方式,但是后面源码显示明显不是

null, 分解器?

options); bundle

可以猜想:

ams首先通过当前的标识token,从保存的AR里面去判断当前的界面存在不存在,是系统的还是应用的,是什么生命周期下的等等

然后ams,解析intent,获取到要启动的界面的包名,类名等信息,用来创建一个AR与之对应,同事AR存入TR,TR存入AS,AS存入ASS(中间涉及WMS和堆栈管理大致了解就行吧)

最后ams的管理工作完成,还要通知当前界面继续你的启动任务,就使用IApplicationThread这个binder通讯 *

AMS进程

通过binder通讯,调到ActivityManagerService

ActivityManagerService源码摘取分析:

public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}


*通过参数分析功能:只多了一个UserHandle,这个在前面launch的地方也是起到了判断的作用

UserHandle user = item == null ? null : item.user;判断….

注解说:在设备上的用户表示。在ums的啥时候再说吧,目前他就是一个系统原来判定是不是同一个使用者的工具*

public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);

//后加的api  ActivityStarter
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null,
"startActivityAsUser");
}


ActivityStarter源码摘取分析:(从4.2之前的AMS和AS直接调用,改为添加了一个starter,就是应为4.2以后,安卓系统支持了多用户功能,同时也新增了UMS机制,这也就是上面那个UserHandle的原理吧,不懂….)

final int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, WaitResult outResult,
Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask, String reason) {

//保存一个原封不动的intent
final Intent ephemeralIntent = new Intent(intent);
//解析
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);
....
// 解析intent信息
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
//封装动画资源
ActivityOptions options = ActivityOptions.fromBundle(bOptions);

//native的方法,取pid和uid信息
final int realCallingPid = Binder.getCallingPid();
final int realCallingUid = Binder.getCallingUid();
int callingPid;
if (callingUid >= 0) {
callingPid = -1;
} else if (caller == null) {
callingPid = realCallingPid;
callingUid = realCallingUid;
} else {
callingPid = callingUid = -1;
}

//新启动界面,堆信息为当前交互的堆
final ActivityStack stack;
if (container == null || container.mStack.isOnHomeDisplay()) {
stack = mSupervisor.mFocusedStack;
} else...

//创建AR数组
final ActivityRecord[] outRecord = new ActivityRecord[1];

int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor,
resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, outRecord, container,
inTask, reason);

}

int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask, String reason) {

if (TextUtils.isEmpty(reason)) {
throw new IllegalArgumentException("Need to specify a reason.");
}
mLastStartReason = reason;   //"startActivityAsUser"
mLastStartActivityTimeMs = System.currentTimeMillis();
mLastStartActivityRecord[0] = null;    //AR数组

mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
container, inTask);

//确保是空的
if (outActivity != null) {
// mLastStartActivityRecord[0] is set in the call to startActivity above.
outActivity[0] = mLastStartActivityRecord[0];
}
}

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask) {

//取数据
final Bundle verificationBundle
= options != null ? options.popAppVerificationBundle() : null;

//获取当前调用界面(launch)的进程信息PR
ProcessRecord callerApp = null;
if (caller != null) {
//获取过程放下面
callerApp = mService.getRecordForAppLocked(caller); //caller是IApplicationThread,binder对象,所以这个binder既用来通讯,又是标识
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else ...
}

//检测权限
boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity, callerApp,
resultRecord, resultStack, options);

//**创建 ActivityRecord**
//**构建ActivityRecord时,构建IApplicationToken.Stub appToken = new Token(this); **
ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
mSupervisor, container, options, sourceRecord);

return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
options, inTask, outActivity);

}


PR获取过程:

final ProcessRecord getRecordForAppLocked(

IApplicationThread thread) {

if (thread == null) {

return null;

}

int appIndex = getLRURecordIndexForAppLocked(thread);
if (appIndex >= 0) {
return mLruProcesses.get(appIndex);
}

// 如果最近使用的PR表里没有,那么这个PR应该不存在,但是还是严谨的在全部数据中查询了一遍
final IBinder threadBinder = thread.asBinder();
final ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
for (int i = pmap.size()-1; i >= 0; i--) {
final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
for (int j = procs.size()-1; j >= 0; j--) {
final ProcessRecord proc = procs.valueAt(j);
if (proc.thread != null && proc.thread.asBinder() == threadBinder) {
Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
+ proc);
return proc;
}
}
}

return null;
}


mProcessNames,在上一篇介绍过,现在看mLruProcesses,

final ArrayList mLruProcesses = new ArrayList();

是一个有序的PR集合。操作的过程后面再说

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {

result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
}

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {

//栈判断和操作TR
final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
? mSourceRecord.getTask() : null;

// Should this be considered a new task?
int result = START_SUCCESS;
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
//创建新栈
result = setTaskFromReuseOrCreateNewTask(
taskToAffiliate, preferredLaunchStackId, topStack);
} else if (mSourceRecord != null) {
result = setTaskFromSourceRecord();
} else if (mInTask != null) {
result = setTaskFromInTask();
} else {
// This not being started from an existing activity, and not part of a new task...
// just put it in the top task, though these days this case should never happen.
setTaskToCurrentTopOrCreateNewTask();
}

if (dontStart) {
//检测权限
mService.grantUriPermissionFromIntentLocked(mCallingUid, mStartActivity.packageName,
mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.userId);

if (mDoResume) {
mSupervisor.resumeFocusedStackTopActivityLocked();
}
}
}


创建栈TR:

private int setTaskFromReuseOrCreateNewTask(
TaskRecord taskToAffiliate, int preferredLaunchStackId, ActivityStack topStack) {

mTargetStack = computeStackFocus(
mStartActivity, true, mLaunchBounds, mLaunchFlags, mOptions);
if (mReuseTask == null) {
final TaskRecord task = mTargetStack.createTaskRecord(
mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId),
mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info,
mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession,
mVoiceInteractor, !mLaunchTaskBehind /* toTop */, mStartActivity.mActivityType);

addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask");
if (mLaunchBounds != null) {
final int stackId = mTargetStack.mStackId;
if (StackId.resizeStackWithLaunchBounds(stackId)) {
mService.resizeStack(
stackId, mLaunchBounds, true, !PRESERVE_WINDOWS, ANIMATE, -1);
} else {
mStartActivity.getTask().updateOverrideConfiguration(mLaunchBounds);
}
}
} else {
addOrReparentStartingActivity(mReuseTask, "setTaskFromReuseOrCreateNewTask");
}

if (taskToAffiliate != null) {
mStartActivity.setTaskToAffiliateWith(taskToAffiliate);
}

if (mSupervisor.isLockTaskModeViolation(mStartActivity.getTask())) {
return START_RETURN_LOCK_TASK_MODE_VIOLATION;
}

if (!mMovedOtherTask) {
updateTaskReturnToType(mStartActivity.getTask(), mLaunchFlags,
preferredLaunchStackId != INVALID_STACK_ID ? mTargetStack : topStack);
}
if (mDoResume) {
mTargetStack.moveToFront("reuseO
14d33
rNewTask");
}
return START_SUCCESS;
}


ActivityStackSupervisor 源码摘取分析:

boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}

final ActivityRecord r = mFocusedStack.topRunningActivityLocked();

if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.state == RESUMED) {
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}


获取下一个要启动的AR:

//ActivityStack
private ActivityRecord topRunningActivityLocked(boolean focusableOnly) {
for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked();
if (r != null && (!focusableOnly || r.isFocusable())) {
return r;
}
}
return null;
}
前面说过在AS(堆)中管理这一个成员变量mTaskHistory,ArrayList<TaskRecord> mTaskHistory
里面是TR(栈)的信息,

//TaskRecord
ActivityRecord topRunningActivityLocked() {
if (mStack != null) {
for (int activityNdx = mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
ActivityRecord r = mActivities.get(activityNdx);
if (!r.finishing && r.okToShowLocked()) {
return r;
}
}
}
return null;
}
然后TR(栈)里面管理这一个成员变量mActivities,ArrayList<ActivityRecord> mActivities
里面是AR(界面)的信息

同时可以看到都是有序集合,即堆中栈排序按照一定顺序,栈中界面按照一定顺序(显示顺序)

//保存TR到AS中,并进行管理
ActivityStack
final void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
boolean newTask, boolean keepCurTransition, ActivityOptions options) {

TaskRecord rTask = r.getTask();
final int taskId = rTask.taskId;
if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
insertTaskAtTop(rTask, r);
}
}

private void insertTaskAtTop(TaskRecord task, ActivityRecord starting) {
updateTaskReturnToForTopInsertion(task);
mTaskHistory.remove(task);
final int position = getAdjustedPositionForTask(task, mTaskHistory.size(), starting);
mTaskHistory.add(position, task);
updateTaskMovement(task, true);
mWindowContainerController.positionChildAtTop(task.getWindowContainerController(),
true /* includingParents */);
}

/** Returns the position the input task should be placed in this stack. */
int getAdjustedPositionForTask(TaskRecord task, int suggestedPosition,
ActivityRecord starting) {

int maxPosition = mTaskHistory.size();
if ((starting != null && starting.okToShowLocked())
|| (starting == null && task.okToShowLocked())) {
// If the task or starting activity can be shown, then whatever position is okay.
return Math.min(suggestedPosition, maxPosition);
}

// The task can't be shown, put non-current user tasks below current user tasks.
while (maxPosition > 0) {
final TaskRecord tmpTask = mTaskHistory.get(maxPosition - 1);
if (!mStackSupervisor.isCurrentProfileLocked(tmpTask.userId)
|| tmpTask.topRunningActivityLocked() == null) {
break;
}
maxPosition--;
}

return  Math.min(suggestedPosition, maxPosition);
}


ActivityStack 源码摘取分析:

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
return false;
}

boolean result = false;
try {
mStackSupervisor.inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
mStackSupervisor.checkReadyForSleepLocked();
return result;
}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

//获取下一个要获取焦点的界面(要打开的界面),从这点可以看出开启一个界面前,先需要把AR添加到TR的顶部
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);

//如果要启动的界面就是当前的界面,什么也不做
//代码略

//如果当前正在交互的界面不是空,其实也判定了不是要启动的界面,就先执行当前界面的Pause
if (mResumedActivity != null) {
pausing |= startPausingLocked(userLeaving, false, next, false);
}

//如果当前的进程不是空next.app != null,并且用于通讯的binder也不是空next.app.thread != null,即当前进程已经存在,直接调回客户应用进程的resume
if (next.app != null && next.app.thread != null) {
try{
next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
mService.isNextTransitionForward(), resumeAnimOptions);
} catch (Exception e) {
mStackSupervisor.startSpecificActivityLocked(next, true, false);
}
} else {
//否者去创建
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}


ActivityStackSupervisor的startSpecificActivityLocked()方法,前面已经分析过了,zygote创建新的进程

在AMS中:

创建ProcessRecord,代表进程,

添加到AMS的ProcessMap中管理,

使用getProcessRecordLocked()方法可以进行查询

我们现在是从桌面Launch界面要开启其他应用,所以mResumedActivity != null,并且next != Launch

所以会先进行Launch的pause。

ActivityStack 源码摘取分析:

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean pauseImmediately) {

//暂停当前的界面时,先判定有没有要暂停的界面
if (mPausingActivity != null) {
if (!mService.isSleepingLocked()) {
//完成暂停,继续其他工作
completePauseLocked(false, resuming);
}
}

//获取当前的界面
ActivityRecord prev = mResumedActivity;

//前后俩个方法都判断过当前的界面mResumedActivity,todo需要查看mResumedActivity赋值的地方
if (prev == null) { //当前没有交互的界面执行
if (resuming == null) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
return false;
}

//判定父界面为空时,就查询mActivityDisplays中的该父界面的堆
if (mActivityContainer.mParentActivity == null) {
mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, pauseImmediately);
}

mResumedActivity = null;       //当前的界面置为空
mPausingActivity = prev;       //把当前的界面置为要暂停的界面
mLastPausedActivity = prev;
mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
|| (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
prev.state = ActivityState.PAUSING;     //更改状态

if (prev.app != null && prev.app.thread != null) {

prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,  //利用binder回调回客户应用进程,pause
userLeaving, prev.configChangeFlags, pauseImmediately);

//下面的捕获和else都是更改状态
...catch (Exception e) {
// Ignore exception, if process died other code will cleanup.
Slog.w(TAG, "Exception thrown during pause", e);
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}

//由上面的更改的mPausingActivity的状态继续下面的流程
if (mPausingActivity != null) {
if (pauseImmediately) {                    //立即暂停mPausingActivity
completePauseLocked(false, resuming);
return false;
} else {
schedulePauseTimeout(prev);            //延时暂停
return true;
}
} else {
if (resuming == null) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
return false;
}

}

private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {

//当前执行暂停的界面
ActivityRecord prev = mPausingActivity;

if (prev != null) {
final boolean wasStopping = prev.state == STOPPING;   //判定当前界面是否是stop状态
prev.state = ActivityState.PAUSED;
if (prev.finishing) { //如果是正在finishing的状态,就执行finish流程
prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
} else if (prev.app != null) {
...
addToStopping(prev, true /* scheduleIdle */, false /* idleDelayed */);   //当前界面的onstop流程
}
}

//执行要启动的界面的流程
if (resumeNext) {
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
if (!mService.isSleepingOrShuttingDownLocked()) {
mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
} else {
mStackSupervisor.checkReadyForSleepLocked();
ActivityRecord top = topStack.topRunningActivityLocked();
if (top == null || (prev != null && top != prev)) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
}
}
}


onstop(),(通过前面的onpause流程可以猜想,最终一定会调用到app.thread.scheduleStopActivity()方法)

void addToStopping(ActivityRecord r, boolean scheduleIdle, boolean idleDelayed) {

//ASS中维护者一个mStoppingActivities,保存所有进入stop的界面ArrayList<ActivityRecord> mStoppingActivities
if (!mStackSupervisor.mStoppingActivities.contains(r)) {
mStackSupervisor.mStoppingActivities.add(r);
}

boolean forceIdle = mStackSupervisor.mStoppingActivities.size() > MAX_STOPPING_TO_FORCE  //要stop的界面多余3个
|| (r.frontOfTask && mTaskHistory.size() <= 1);                           //如果当前的界面是栈底r.frontOfTask, mTaskHistory前面介绍过是AS中维护的栈

if (scheduleIdle || forceIdle) {
if (!idleDelayed) {                          //是否要延时
mStackSupervisor.scheduleIdleLocked();                     //最终都会进入scheduleIdleLocked()
} else {
mStackSupervisor.scheduleIdleTimeoutLocked(r);
}
} else {
mStackSupervisor.checkReadyForSleepLocked();
}
}

//ASS
final void scheduleIdleLocked() {
mHandler.sendEmptyMessage(IDLE_NOW_MSG);   //ASS也使用handler机制
}

case IDLE_NOW_MSG: {
activityIdleInternal((ActivityRecord) msg.obj, false /* processPausingActivities */);
} break;

void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) {
synchronized (mService) {
activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */,
processPausingActivities, null);
}
}

final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
boolean processPausingActivities, Configuration config) {

for (int i = 0; i < NS; i++) {
r = stops.get(i);
final ActivityStack stack = r.getStack();
if (stack != null) {
if (r.finishing) {
stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
} else {
stack.stopActivityLocked(r);
}
}
}
}

final void stopActivityLocked(ActivityRecord r) {
if (r.app != null && r.app.thread != null) {
adjustFocusedActivityStackLocked(r, "stopActivity");
r.resumeKeyDispatchingLocked();
try {
r.stopped = false;
r.state = STOPPING;
if (!r.visible) {
r.setVisible(false);
}
r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);     //前面猜的得到了验证
if (mService.isSleepingOrShuttingDownLocked()) {
r.setSleeping(true);
}
Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
} catch (Exception e) {
r.stopped = true;
r.state = STOPPED;
if (r.deferRelaunchUntilPaused) {
destroyActivityLocked(r, true, "stop-except");
}
}
}
}

case STOP_TIMEOUT_MSG: {
ActivityRecord r = (ActivityRecord)msg.obj;
synchronized (mService) {
if (r.isInHistory()) {
r.activityStoppedLocked(null /* icicle */,
null /* persistentState */, null /* description */);
}
}
} break;


新界面的oncreate()流程:

//执行要启动的界面的流程
if (resumeNext) {
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
if (!mService.isSleepingOrShuttingDownLocked()) {
mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
} else {
mStackSupervisor.checkReadyForSleepLocked();
ActivityRecord top = topStack.topRunningActivityLocked();
if (top == null || (prev != null && top != prev)) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
}
}

ASS
boolean resumeFocusedStackTopActivityLocked() {
return resumeFocusedStackTopActivityLocked(null, null, null);
}

boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.state == RESUMED) {
// Kick off any lingering app transitions form the MoveTaskToFront operation.
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}

AS
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

mStackSupervisor.startSpecificActivityLocked(next, true, false);

}

ASS
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {

//获取进程信息
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);

r.getStack().setLaunchTime(r);

if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
mService.mProcessStats);
}
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch ....
}

mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,       //上一篇说过了,创建新进程PR,然后启动应用进程的ActivityThread
"activity", r.intent.getComponent(), false, false, true);
}


APP进程

ActivityThread:(进程创建好后,会调用AT的main)

public static void main(String[] args) {
ActivityThread thread = new ActivityThread();
thread.attach(false);
Looper.loop();
}

private void attach(boolean system) {
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread);    //又进入ams中执行attachApplication
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}

public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
attachApplicationLocked(thread, callingPid);
}
}

private final boolean attachApplicationLocked(IApplicationThread thread,
int pid) {

//进程检查
ProcessRecord app;
if (pid != MY_PID && pid >= 0) {
synchronized (mPidsSelfLocked) {
app = mPidsSelfLocked.get(pid);
}
} else {
app = null;
}

if (app == null) {
if (pid > 0 && pid != MY_PID) {
//非系统应用,杀掉进程
killProcessQuiet(pid);
} else {
try {
//退出应用进程
thread.scheduleExit();
} catch (Exception e) {
}
}
return false;
}

//检查通讯binder,如果存在证明是以前的,就进行清除
if (app.thread != null) {
handleAppDiedLocked(app, true, true);
}

//里面涉及到内存,和进程排序
updateProcessForegroundLocked(app, false, false);

//调回应用进程的绑定
if (app.instr != null) {
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial);
} else {
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial);
}

//系统中进程也是lru方式保存和使用的
updateLruProcessLocked(app, false, null);

// 看看顶部可见的活动是否正在等待在这个过程中运行…
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {  //就是当前正在等待oncreate的正常情况
didSomething = true;
}
} catch (Exception e) {
badApp = true;
}
}

// 查找在此过程中应该运行的任何服务…(运行服务)
if (!badApp) {
try {
didSomething |= mServices.attachApplicationLocked(app, processName);
} catch (Exception e) {
badApp = true;
}
}

// 检查下一个广播接收器是否在这个过程中…(运行广播接收者)
if (!badApp && isPendingBroadcastProcessLocked(pid)) {
try {
didSomething |= sendPendingBroadcastsLocked(app);
} catch (Exception e) {
badApp = true;
}
}

// 检查下一个备份代理是否在这个过程中…
if (!badApp && mBackupTarget != null && mBackupTarget.app == app) {
notifyPackageUse(mBackupTarget.appInfo.packageName,
PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
try {
thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
mBackupTarget.backupMode);
} catch (Exception e) {
badApp = true;
}
}

//退出
if (badApp) {
app.kill("error during init", true);
handleAppDiedLocked(app, false, true);
return false;
}

//更新内存信息
if (!didSomething) {
updateOomAdjLocked();
}

}

ASS
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
//SparseArray<ActivityDisplay> mActivityDisplays 应该是和wms交互用的
ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
//发现保存界面栈信息的堆,保存在了和窗口交互的mActivityDisplays里,是不是就可以理解一个堆,就是一层窗口
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = stacks.get(stackNdx);
//获取当前正在交互的堆(窗口)
if (!isFocusedStack(stack)) {
continue;
}
//从堆中获取要启动的AR
ActivityRecord hr = stack.topRunningActivityLocked();
if (hr != null) {
if (hr.app == null && app.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
//真正的启动该界面
if (realStartActivityLocked(hr, app, true, true)) {
didSomething = true;
}
} catch (RemoteException e) {
throw e;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
return didSomething;
}

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {

//调回应用进程
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global and
// override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, !andResume,
mService.isNextTransitionForward(), profilerInfo);

}


上面的binder就是这个ApplicationThread,作用之一就是用来通讯(ams和app之间)

private class ApplicationThread extends IApplicationThread.Stub {

//前面的launch界面pause过程,调到了自己进程的这个方法
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
configChanges,
seq);
}

@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

updateProcessState(procState, false);

//创建应用ACR对应AMS中AR
ActivityClientRecord r = new ActivityClientRecord();

r.token = token;
r.ident = ident;
r.intent = intent;
r.referrer = referrer;
r.voiceInteractor = voiceInteractor;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;
r.persistentState = persistentState;

r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;

r.startsNotResumed = notResumed;
r.isForward = isForward;

r.profilerInfo = profilerInfo;

r.overrideConfig = overrideConfig;
updatePendingConfiguration(curConfig);

sendMessage(H.LAUNCH_ACTIVITY, r);
}

//挑几个熟悉的放到上面
//activity生命周期
public final void scheduleNewIntent(
List<ReferrerIntent> intents, IBinder token, boolean andPause) {
NewIntentData data = new NewIntentData();
data.intents = intents;
data.token = token;
data.andPause = andPause;

sendMessage(H.NEW_INTENT, data);
}

public final void scheduleDestroyActivity(IBinder token, boolean finishing,
int configChanges) {
sendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
configChanges);
}

public final void scheduleResumeActivity(IBinder token, int processState,
boolean isForward, Bundle resumeArgs) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "resumeActivity " + ActivityThread.this
+ " operation received seq: " + seq);
updateProcessState(processState, false);
sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0, 0, seq);
}

public final void scheduleStopActivity(IBinder token, boolean showWindow,
int configChanges) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "stopActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
token, 0, configChanges, seq);
}

//服务生命周期
public final void scheduleCreateService(IBinder token,
ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
updateProcessState(processState, false);
CreateServiceData s = new CreateServiceData();
s.token = token;
s.info = info;
s.compatInfo = compatInfo;

sendMessage(H.CREATE_SERVICE, s);
}

public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
updateProcessState(processState, false);
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;
s.rebind = rebind;

if (DEBUG_SERVICE)
Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
sendMessage(H.BIND_SERVICE, s);
}

public final void scheduleCreateService(IBinder token,
ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
updateProcessState(processState, false);
CreateServiceData s = new CreateServiceData();
s.token = token;
s.info = info;
s.compatInfo = compatInfo;

sendMessage(H.CREATE_SERVICE, s);
}

public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
updateProcessState(processState, false);
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;
s.rebind = rebind;

if (DEBUG_SERVICE)
Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
sendMessage(H.BIND_SERVICE, s);
}

public final void scheduleUnbindService(IBinder token, Intent intent) {
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;

sendMessage(H.UNBIND_SERVICE, s);
}

//广播吧
public final void scheduleReceiver(Intent intent, ActivityInfo info,
CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
boolean sync, int sendingUser, int processState) {
updateProcessState(processState, false);
ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
sync, false, mAppThread.asBinder(), sendingUser);
r.info = info;
r.compatInfo = compatInfo;
sendMessage(H.RECEIVER, r);
}

public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
sendMessage(
showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
token);
}

public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
ResultData res = new ResultData();
res.token = token;
res.results = results;
sendMessage(H.SEND_RESULT, res);
}

// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

updateProcessState(procState, false);

ActivityClientRecord r = new ActivityClientRecord();

r.token = token;
r.ident = ident;
r.intent = intent;
r.referrer = referrer;
r.voiceInteractor = voiceInteractor;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;
r.persistentState = persistentState;

r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;

r.startsNotResumed = notResumed;
r.isForward = isForward;

r.profilerInfo = profilerInfo;

r.overrideConfig = overrideConfig;
updatePendingConfiguration(curConfig);

sendMessage(H.LAUNCH_ACTIVITY, r);
}

@Override
public final void scheduleRelaunchActivity(IBinder token,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
int configChanges, boolean notResumed, Configuration config,
Configuration overrideConfig, boolean preserveWindow) {
requestRelaunchActivity(token, pendingResults, pendingNewIntents,
configChanges, notResumed, config, overrideConfig, true, preserveWindow);
}

public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial) {

if (services != null) {
// Setup the service cache in the ServiceManager
ServiceManager.initServiceCache(services);
}

setCoreSettings(coreSettings);

AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providers;
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
sendMessage(H.BIND_APPLICATION, data);
}
...

}


前面分析过,首次启动界面会创建进程,进程创建完毕后,会启动activityThread的main,

在main中会创建消息队列,一直轮询的处理事件。利用handler机制。这个地方ams传回pause的事件,也是这样处理的

来看handler中对应的case:

case PAUSE_ACTIVITY: {
handlePauseActivity((IBinder) args.arg1, false,
(args.argi1 & USER_LEAVING) != 0, args.argi2,
(args.argi1 & DONT_REPORT) != 0, args.argi3);
} break;

private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport, int seq) {

//获取当前要pause的界面的代表类
ActivityClientRecord r = mActivities.get(token);

if (r != null) {

//执行pause
performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");

//通知ams,已经pause
if (!dontReport) {
try {
ActivityManager.getService().activityPaused(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
mSomeActivitiesChanged = true;
}
}

final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
//在应用本地,存在一个保存activity的map,标识就是这个token(在创建AR时候创建的,是activity的标识,由ams穿到了本地)
//赋值的位置在performLaunchActivity()中

final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState, String reason) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState, reason) : null;
}

final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState, String reason) {

performPauseActivityIfNeeded(r, reason);

}

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
mInstrumentation.callActivityOnPause(r.activity);
}

//Instrumentation中
public void callActivityOnPause(Activity activity) {
activity.performPause();
}

//Activity
final void performPause() {
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;

//调用onPause
onPause();
//交互状态为false
mResumed = false;
if (!mCalled && getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPause()");
}
mResumed = false;
}

case LAUNCH_ACTIVITY: {
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
} break;

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {

//wms机制的东西初始化
WindowManagerGlobal.initialize();
//调用activity的oncreate和onstart
Activity a = performLaunchActivity(r, customIntent);
//调用activity的onresume,之后该界面会持续保持在交互状态,知道下一个启动界面的行为发生,即从新开始上面流程(注意没有特殊设置,进程不会重新创建,但是AMS和AT的管理和操作是不变的)
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}

ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}

if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}

//上下文
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();

//创建activity(反射构造),所以activity没有new出来的,我们启动也是传递的class
//应为new出来的activity,只是普通对象,没有任何activity的属性,以及生命周期
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
}

try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);  //创建Application

if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); //label属性
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
Window window = null;                                            //窗口
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
appContext.setOuterContext(activity);

//挂接,这也就是前面我们在pause流程中,用到哪些标识token,通讯用的binder的赋值过程
//即首次启动时,进行赋值
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback);

if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}

activity.mCalled = false;

//调用oncreate
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
r.stopped = true;

//调用onstart
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
if (r.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
if (!activity.mCalled) {
}
}
}
r.paused = true;

mActivities.put(r.token, r);

} catch (SuperNotCalledException e) {
} catch (Exception e) {
}

return activity;
}

LoadedApk
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}

Application app = null;

String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}

try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader();  //非安卓包
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);

//创建 Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
}

//通过这据代码,AT可以理解为所有应用在客户端的大管家
mActivityThread.mAllApplications.add(app);
mApplication = app;

if (instrumentation != null) {
try {
//Application 的  OnCreate
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
}
}

//改写所有库apk的R“常量”。
SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers();
final int N = packageIdentifiers.size();
for (int i = 0; i < N; i++) {
final int id = packageIdentifiers.keyAt(i);
if (id == 0x01 || id == 0x7f) {
continue;
}

rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
}

return app;
}

static public Application newApplication(Class<?> clazz, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = (Application)clazz.newInstance();  //反射构造
app.attach(context);           //挂接方法
return app;
}


最后调用生命周期的oncreate

public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);             //  ActivityWaiter   服务员
activity.performCreate(icicle);
postPerformCreate(activity);            //  ActivityMonitor  监管员
}

activity
final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle);                      //  生命周期之onCreate
mActivityTransitionState.readState(icicle);
performCreateCommon();
}


至此:从一个界面(本例是系统launch桌面)启动另一个界面的流程分析完毕

client:

launch界面,带着要启动的信息(intent)通过Instrumentation(执行者),利用binder通讯(ApplicationThread),进入系统ams机制下处理

ams:

1.解析intent和bundle

2.创建AR,对应activity

3.创建TR,进行AR的操作和管理

4.保存TR到AS中,进行操作和管理

5.进行当前界面的pause,和新界面的create

pause,更改AMS中AR状态,利用binder回调client中

handler消息机制–》Instrumentation(执行者)–》activity.onpause

完成pause,

handler消息机制–》Instrumentation(执行者)–》activity.onstop

create:

创建进程,进程创建完成,启动client的ActivityThread.main

消息机制开启Looper

main中,利用binder,进入ams,获取前面存的AR,进行启动,

attach到AMS,ams控制状态,回调到client

创建ACR与AR对应,创建activity,创建Application, attach app, attach act

然后Instrumentation执行oncreate,onstart

最终执行handleResumeActivity()保持新界面处于一直交互状态

完成

其实ams像是一个大脑,由它命令所有客户端进程界面执行生命周期的每个方法

而实际执行的是在客户端的进程中,ams负责权限检查,页面层次,页面状态的控制等

遗留俩个问题:

1.其实上面只有界面的生命周期,并没有真正意义上控制到界面的显影,所以接下来分析这个(wms)

2.现在大致知道ASS管理AS,AS管理TR,TR管理AR,那么怎么管理的呢。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android