上一篇我们已经发分析了Launcher启动起来后,如何将应用程序封装成桌面图标,并设置了点击事件监听的整个流程。当点击桌面图标,就会执行Activity的startActivity方法。
Activity的启动分2种,即根Activity和子ACtivity。根Activity的启动就代表了一个应用程序的启动过程,子Activity有可能和启动它们的Activity运行在同一个进程,也可能不同进程。这里需要注意的是,我们以当前是在Launcher这个Activity中执行跳转,启动新应用程序的根Activity为分析。
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback {
......
//跳转请求
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
//关键方法,通过Instrumentation启动Activity
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
......
}
Instrumentation用来监控应用程序和系统之间的交互操作,系统要启动Activity,需要使用Instrumentation来启动,Launcher的Instrumentation在前面分析过,它在ActivityThread的attach方法中被构造出来,传递给Activity的attach方法。
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
//不是系统进程
if (!system) {
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",UserHandle.myUserId());
try {
//创建Instrumentation
mInstrumentation = new Instrumentation();
//创建Application上下文
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
//创建Application
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
execStartActivity的几个参数都很重要:
- mMainThread为ActivityThread,表示了应用程序的主线程,这里表示了Launcher这个应用程序的主线程。
- mMainThread.getApplicationThread()取得的是ApplicationThread,它ActivityThread的内部类,为Binder类型。
将ApplicationThread传给Instrumentation,Instrumentation会传递给AMS,用于ActivityThread和AMS之间的通讯。 - 每启动一个Activity,在AMS中都有对应的一个ActivityRecord来记录Activity的运行状况,这里的mToken为IBinder类型,同样传递给了AMS,用来指向ActivityRecord。
这些关键点,会再下面分析到,我们继续看execStartActivity方法。
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
//获得AMS代理对象启动Activity
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
return null;
}
Launcher界面运行在自己的进程中,AMS也运行在自己的进程中,这是一个跨进程的通讯,因此,Launcher必须先获得AMS的远程代理Binder,才能向AMS发送数据。
getDefault()获得一个AMS的代理对象ActivityManagerProxy,调用startActivity将数据传递给AMS,通知AMS启动新的Activity。先看代理的获取过程。
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
//获取代理
static public IActivityManager getDefault() {
return gDefault.get();
}
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
//获取系统级Service,即ActivityManagerService
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
//转化成ActivityManagerProxy代理类
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
Singleton是一个单例模板类。
public abstract class Singleton<T> {
private T mInstance;
protected abstract T create();
public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
显然,将T换为IActivityManager 就可以了。create() 方法会从ServiceManager中查询并返回AMS服务的远程代理,关于Binder跨进程通讯,在Binder系列已经做了详细分析,这里我们看下AMS被添加注册到ServiceManager中,它在启动SystemServer时被注册的。
public final class SystemServer {
.......
public static void main(String[] args) {
new SystemServer().run();//执行run
}
private void run() {
......
try {
//启动服务,创建PMS,AMS等
startBootstrapServices();
// 启动核心服务
startCoreServices();
//启动IputManagerService等
startOtherServices();
......
}
private void startBootstrapServices() {
mInstaller = mSystemServiceManager.startService(Installer.class);
//开启ActivityManagerService,对比PowerManagerService等,实际上ActivityManagerService不是一个SystemService,而是Binder,ActivityManagerService.Lifecycle才是SystemService
mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//开启mPowerManagerService
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mActivityManagerService.initPowerManagement();
//开启mDisplayManagerService
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
}
//构建PackageManagerService
mPackageManagerService = PackageManagerService.main(mSystemContext, mInstaller,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());
AttributeCache.init(mSystemContext);
//将AMS注册到ServiceManager中
mActivityManagerService.setSystemProcess();
}
Lifecycle是ActivityManagerService的内部类,它继承SystemService。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
//构建ActivityManagerService
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
mService.start();
}
public ActivityManagerService getService() {
return mService;
}
}
在Lifecycle构造了ActivityManagerService,通过getService方法获取,最后我们看setSystemProcess方法。
public void setSystemProcess() {
try {
//将ActivityManagerService注册到ServiceManager中
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
ServiceManager.addService("permission", new PermissionController(this));
......
}
可以预见这里的Context.ACTIVITY_SERVICE就是"activity",它把this即ActivityManagerService添加到ServiceManager中。
public abstract class Context {
......
public static final String ACTIVITY_SERVICE = "activity";
......
}
这也对应了上面的getService("activity"),返回IActivityManagerService,随后又通过asInterface(b)转化成IActivityManager,它的原型是ActivityManagerProxy。
......
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IActivityManager in = (IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
//构建ActivityManagerProxy
return new ActivityManagerProxy(obj);
}
......
这里使用了静态代理模式,ActivityManagerProxy实现了IActivityManager。
class ActivityManagerProxy implements IActivityManager{
public ActivityManagerProxy(IBinder remote)
{
mRemote = remote;
}
public IBinder asBinder()
{
return mRemote;
}
//将数据发送给AMS
public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
//caller指向Laucher的ApplicationThread
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
data.writeString(callingPackage);
//intent包含启动组件MainActivity的信息
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
//resultTo指向AMS内部的一个ActivityRecord
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(startFlags);
if (profilerInfo != null) {
data.writeInt(1);
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
if (options != null) {
data.writeInt(1);
options.writeToParcel(data, 0);
} else {
data.writeInt(0);
}
//通过Binder对象mRemote,向AMS发送START_ACTIVITY_TRANSACTION的信息,开启Activity
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
//读取响应数据
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
mRemote通过transact向AMS发送了Parcel 数据,这里有三个数据比较重要,即caller、intent和resultTo,注释里都做了说明。这样,数据就跨进程传递给了AMS,需要注意的是AMS也继承了ActivityManagerNative。
@Override
public int startActivity(IBinder whoThread, String callingPackage,
Intent intent, String resolvedType, Bundle options) {
checkCaller();
int callingUser = UserHandle.getCallingUserId();
TaskRecord tr;
IApplicationThread appThread;
synchronized (ActivityManagerService.this) {
tr = recentTaskForIdLocked(mTaskId);
if (tr == null) {
throw new IllegalArgumentException("Unable to find task ID " + mTaskId);
}
appThread = ApplicationThreadNative.asInterface(whoThread);
if (appThread == null) {
throw new IllegalArgumentException("Bad app thread " + appThread);
}
}
//通过StackSupervisor,ActivityStack的管理器,调用startActivityMayWait
return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent,
resolvedType, null, null, null, null, 0, 0, null, null,
null, options, callingUser, null, tr);
}
AMS接收到START_ACTIVITY_TRANSACTION就会调用内部的startActivity方法。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, options,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
false, ALLOW_FULL_ONLY, "startActivity", null);
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, userId, null, null);
}
......
转入到ActivityStackSupervisor栈管理中进行Activity的启动。
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 config,
Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {
if (intent != null && intent.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
boolean componentSpecified = intent.getComponent() != null;
intent = new Intent(intent);
ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
profilerInfo, userId);
.....
try {
//通过PackageManager得到ActivityInfo列表,每个ActivityInfo是一个Activity的档案对象,记录了Activity相关信息
//这里获取到启动入口的Activity信息
ResolveInfo rInfo = AppGlobals.getPackageManager().resolveIntent(
intent, null,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS, userId);
aInfo = rInfo != null ? rInfo.activityInfo : null;
aInfo = mService.getActivityInfoForUser(aInfo, userId);
} catch (RemoteException e) {
aInfo = null;
}
}
}
}
//验证Intent、class等信息
int res = startActivityLocked(caller, intent, resolvedType, aInfo,
voiceSession, voiceInteractor, resultTo, resultWho,
requestCode, callingPid, callingUid, callingPackage,
realCallingPid, realCallingUid, startFlags, options,
componentSpecified, null, container, inTask);
......
return res;
}
}
startActivityLocked会对Intent包含的跳转信息进行验证。
final int startActivityLocked(IApplicationThread caller,
Intent intent, String resolvedType, ActivityInfo aInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode,
int callingPid, int callingUid, String callingPackage,
int realCallingPid, int realCallingUid, int startFlags, Bundle options,
boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,
TaskRecord inTask) {
int err = ActivityManager.START_SUCCESS;
//ProcessRecord用来描述一个应用程序的进程,并保存在AMS内部
ProcessRecord callerApp = null;
if (caller != null) {
//从getRecordForAppLocked获取ProcessRecord
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;//获取进程pid
callingUid = callerApp.info.uid;//获取进程uid
} else {
err = ActivityManager.START_PERMISSION_DENIED;
}
}
if (err == ActivityManager.START_SUCCESS) {
final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
}
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
sourceRecord = isInAnyStackLocked(resultTo);;
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;
......
//创建ActivityRecord
ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
requestCode, componentSpecified, this, container, options);
......
//验证完成,开始启动模式判断
err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, true, options, inTask);
if (err < 0) {
notifyActivityDrawnForKeyguard();
}
return err;
}
callerApp 为ProcessRecord类型,用来描述一个应用程序的进程,保存在AMS中,而每个Activity在堆栈中用一个ActivityRecord来描述,随后传递给startActivityUncheckedLocked,根据启动模式启动Activity。
final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
boolean doResume, Bundle options, TaskRecord inTask) {
ActivityStack targetStack;
intent.setFlags(launchFlags);
if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| launchSingleInstance || launchSingleTask) {
if (inTask == null && r.resultTo == null) {
ActivityRecord intentActivity = !launchSingleInstance ?
findTaskLocked(r) : findActivityLocked(intent, r.info);
if (intentActivity != null) {
if (isLockTaskModeViolation(intentActivity.task)) {
showLockTaskToast();
Slog.e(TAG, "startActivityUnchecked: Attempt to violate Lock Task Mode");
return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
}
if (r.task == null) {
r.task = intentActivity.task;
}
//获取对应任务栈
targetStack = intentActivity.task.stack;
......
//从栈开启Activity
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
if (!launchTaskBehind) {
mService.setFocusedActivityLocked(r);
}
return ActivityManager.START_SUCCESS;
}
Intent.FLAG_ACTIVITY_NEW_TASK标志位被置为1,其他位都为0,它表示新启动的Activity会运行在另外一个任务栈中。调用startActivityLocked方法,从指定的任务栈中开启Activity。
final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition, Bundle options) {
TaskRecord rTask = r.task;
final int taskId = rTask.taskId;
if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
insertTaskAtTop(rTask);
mWindowManager.moveTaskToTop(taskId);
}
TaskRecord task = null;
//是否开启新任务栈
if (!newTask) {
......
}
if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
mStackSupervisor.mUserLeaving = false;
}
task = r.task;
//将MainActivity放栈顶
task.addActivityToTop(r);
task.setFrontOfTask();
......
//执行resume
if (doResume) {
//mStackSupervisor是管理stack的,最终由stack任务栈执行resumeTopActivitiesLocked
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
此时为开启新的任务栈,并将ActivityRecord 添加到新栈的最顶端,由前面传入的doResume知道,此时它的值为true。
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
Bundle targetOptions) {
if (targetStack == null) {
targetStack = getFocusedStack();
}
boolean result = false;
//是否栈顶
if (isFrontStack(targetStack)) {
//再次调用了targetStack的resumeTopActivityLocked,此时mResumedActivity==null了
result = targetStack.resumeTopActivityLocked(target, targetOptions);
}
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = stacks.get(stackNdx);
if (stack == targetStack) {
continue;
}
if (isFrontStack(stack)) {
stack.resumeTopActivityLocked(null);
}
}
}
return result;
}
isFrontStack会判断当前的任务栈ActivityStack 是否处于前台,如果处于前台则调用resumeTopActivityLocked方法。
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
if (inResumeTopActivity) {
return false;
}
boolean result = false;
try {
inResumeTopActivity = true;
//进入resumeTopActivityInnerLocked执行pause上一个activity的操作
result = resumeTopActivityInnerLocked(prev, options);
} finally {
inResumeTopActivity = false;
}
return result;
}
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
......
//获取栈顶不是处于结束状态的Activity,next即指向了MainAcivity
ActivityRecord next = topRunningActivityLocked(null);
......
//进入表明,这个Activity已经启动和激活了,无需再启动
if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
mStackSupervisor.allResumedActivitiesComplete()) {
mWindowManager.executeAppTransition();
mNoAnimActivities.clear();
ActivityOptions.abort(options);
mStackSupervisor.notifyActivityDrawnForKeyguard();
return false;
}
......
//先执行当前Activity的Pause,再执行新的resume
boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
if (mResumedActivity != null) {
//执行pause,即Launcher进入Pause,然后再启动next,即MainActivity
pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity);
}
......
//判断新进程是否存在,开启新的activity
mStackSupervisor.startSpecificActivityLocked(next, true, false);
}
这里有3个Activity变量需要解释,mResumedActivity为当前激活的Activity,mLastPausedActivity为上一次中止的Activity,mPausingActivity为正在被终止的Activity,next 为即将启动的Activity,因此,在这里mResumedActivity代表了Launcher。因为此时的mResumedActivity!=null,因此会进入startPausingLocked暂停掉mResumedActivity,再开启目标Acitivity,即next。
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
boolean dontWait) {
if (mPausingActivity != null) {
Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity);
completePauseLocked(false);
}
//Launcher定义成上一个Activity
ActivityRecord prev = mResumedActivity;
if (prev == null) {
if (!resuming) {
Slog.wtf(TAG, "Trying to pause when nothing is resumed");
mStackSupervisor.resumeTopActivitiesLocked();
}
return false;
}
if (mActivityContainer.mParentActivity == null) {
mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
}
//将mPausingActivity和mPausingActivity指向Launcher,并把mResumedActivity值为空
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;
prev.task.touchActiveTime();
clearLaunchTime(prev);
final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
if (mService.mHasRecents && (next == null || next.noDisplay || next.task != prev.task)) {
prev.updateThumbnail(screenshotActivities(prev), null);
}
stopFullyDrawnTraceIfNeeded();
mService.updateCpuStats();
//prev.app记录了这个activity所在的进程,prev.app.thread是ApplicationThread
if (prev.app != null && prev.app.thread != null) {
try {
mService.updateUsageStats(prev, false);
// 让ActivityThread的schedulePauseActivity执行暂停操作,最终回调onPause()方法,并会回到ActivityStack通知已暂停完毕,启动新的Activity
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
} catch (Exception e) {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
if (!mService.isSleepingOrShuttingDown()) {
mStackSupervisor.acquireLaunchWakelock();
}
if (mPausingActivity != null) {
if (!uiSleeping) {
prev.pauseKeyDispatchingLocked();
} else {
if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
}
if (dontWait) {
completePauseLocked(false);
return false;
} else {
//定时启动
Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
msg.obj = prev;
prev.pauseTime = SystemClock.uptimeMillis();
mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
return true;
}
} else {
if (!resuming) {
mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
}
return false;
}
}
mPausingActivity和mPausingActivity指向了Launcher,并把mResumedActivity值为null,随后通过ProcessRecord中的ApplicationThread,通知AcitivityThread暂停掉Launcher,Launcher组件完成暂停后,会向AMS发送一个通知,表示已暂停完毕,AMS就能开启新的Activity,但AMS不能无限地等待,否则出现应用程序无响应,因此只会等待PAUSE_TIMEOUT时长,我们先看Launcher的暂停流程。
//ApplicationThread是ActivityThread的内部类,将从AMS接收到的RPC数据通过消息,传递给ActivityThread
private class ApplicationThread extends ApplicationThreadNative {
......
//收到要暂停Launcher的消息
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
//此时finished为false,userLeaving为true
sendMessage( finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
configChanges);
}
......
}
private void sendMessage(int what, Object obj, int arg1, int arg2) {
sendMessage(what, obj, arg1, arg2, false);
}
//通过mH(Handler)发送消息
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
ApplicationThread 收到暂停的通知,将消息发给Handler处理。
private class H extends Handler {
......
//执行上一个Activity的暂停
case PAUSE_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
(msg.arg1&2) != 0);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
......
}
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
//获取到Launcher的ActivityClientRecord,也就是要暂停的Activity
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
if (userLeaving) {
//1,用户离开事件通知
performUserLeavingActivity(r);
}
r.activity.mConfigChangeFlags |= configChanges;
//2,会执行handlePauseActivity,并调用我们常重写的onPause()
performPauseActivity(token, finished, r.isPreHoneycomb());
if (r.isPreHoneycomb()) {
//3,先保存下数据
QueuedWork.waitToFinish();
}
//4,上面3件事执行完成,通知AMS暂停已执行完毕,可以开始下一个activity了
if (!dontReport) {
try {
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
}
}
mSomeActivitiesChanged = true;
}
}
ActivityThread被当成客户端,而每个Activity都用ActivityClientRecord来记录信息,它对应了AMS的ActivityRecord。这个方法做了4件事:
- 向Launcher组件发送了一个用户离开事件通知,即调用它的成员函数onUserLeaveHint;
- 执行我们熟悉的Activity生命周期方法onPause;
- 将数据进行保存,当重新Resume时,才能保证数据的恢复;
- 最后是向AMS发送通知,Launcher已经Pause完毕了。
这里我们分析第2和4,2会进入performPauseActivity方法。
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState) {
if (r.paused) {
if (r.activity.mFinished) {
return null;
}
}
if (finished) {
r.activity.mFinished = true;
}
try {
if (!r.activity.mFinished && saveState) {
callCallActivityOnSaveInstanceState(r);
}
r.activity.mCalled = false;
//让Instrumentation调用callActivityOnPause,实际调用Activity的performPause
mInstrumentation.callActivityOnPause(r.activity);
......
}
前面说过,instrumentation是一个工具,它用于跟踪Application及Activity生命周期方法。
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
回到Activity的performPause。
final void performPause() {
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;
//onPause()方法执行
onPause();
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;
}
这里我们看到我们熟悉的onPause方法被调用了。接下来,将通知AMS,Launcher已经暂停完成,可以开启新的Activity了,即执行了AMS的activityPaused方法。
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
//栈执行暂停锁定,并开始下一个activity的启动
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
前面说到如果AMS没有在指定时间内收到消息,也会向Handler发送消息,来执行这个方法,如下。
final class ActivityStackHandler extends Handler {
ActivityStackHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PAUSE_TIMEOUT_MSG: {
ActivityRecord r = (ActivityRecord)msg.obj;
synchronized (mService) {
if (r.app != null) {
mService.logAppTooSlow(r.app, r.pauseTime, "pausing " + r);
}
//执行暂停锁定
activityPausedLocked(r.appToken, true);
}
} break;
这个方法被调用,就说明当前的Activity已经完成暂停工作,准备开启下一个Activity。
final void activityPausedLocked(IBinder token, boolean timeout) {
//渠道Launcher的ActivityRecord
final ActivityRecord r = isInStackLocked(token);
if (r != null) {
//把定时删掉,因为Launcher已经在规定事件发送消息给AMS了
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
//正式确定暂停已完成
//开启启动MainActivity
completePauseLocked(true);
} else {
}
}
}
private void completePauseLocked(boolean resumeNext) {
//定义Launcher为prev
ActivityRecord prev = mPausingActivity;
if (prev != null) {
//将Launcher置为Pause状态
prev.state = ActivityState.PAUSED;
if (prev.finishing) {
prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
} else if (prev.app != null) {
if (prev.waitingVisible) {
prev.waitingVisible = false;
mStackSupervisor.mWaitingVisibleActivities.remove(prev);
}
if (prev.configDestroy) {
destroyActivityLocked(prev, true, "pause-config");
} else if (!hasVisibleBehindActivity()) {
mStackSupervisor.mStoppingActivities.add(prev);
if (mStackSupervisor.mStoppingActivities.size() > 3 ||
mStackSupervisor.scheduleIdleLocked();
} else {
mStackSupervisor.checkReadyForSleepLocked();
}
}
} else {
//将其置空,表示终止的Activity已经进入Pause状态
prev = null;
}
mPausingActivity = null;
}
if (resumeNext) {
//暂停完成,获取顶层的ActivityStack
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
//系统是不是睡眠或关闭状态
if (!mService.isSleepingOrShuttingDown()) {
//执行resumeTopActivitiesLocked来开启下一个Activity
mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
} else {
mStackSupervisor.checkReadyForSleepLocked();
ActivityRecord top = topStack.topRunningActivityLocked(null);
if (top == null || (prev != null && top != prev)) {
//执行resumeTopActivitiesLocked来开启下一个Activity
mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
}
}
}
......
}
将Launcher置为Pause状态,以及将mPausingActivity置为null,随后又回到调用resumeTopActivitiesLocked启动位于栈顶的Activity,由于此时的mResumedActivity ==null,因此最终会执行到startSpecificActivityLocked方法。
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//进程描述
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
r.task.stack.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);
}
//启动新activity
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
}
}
//第一次点击图标,进程不在,新建
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
每个Activity都会记录当前的进程名和用户id,如果这个进程存在,就通知进程将这个Activity启动起来不存在则根据进程名和用户id,创建新的进程,再启动新的Activity,由于此处是启动根Activity,因此应用程序的进程还没创建,AMS会通知Zygote创建新的进程,走startProcessLocked方法。这个流程已经在《App桌面图标显示过程》一篇分析过。
AMS会设定一个时间来等待,Zygote进程创建成功后会通知AMS,如果超时了,则AMS会认为创建失败,不启动新的Activity。创建成功,最后调用ActivityThread的main方法。
public final class ActivityThread {
//将从AMS接收到的RPC数据通过消息,传递给ActivityThread
final ApplicationThread mAppThread = new ApplicationThread();
//Handler
final Looper mLooper = Looper.myLooper();
final H mH = new H();
private class ApplicationThread extends ApplicationThreadNative {
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
IVoiceInteractor voiceInteractor, int procState, Bundle state,
PersistableBundle persistentState, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
ProfilerInfo profilerInfo) {
updateProcessState(procState, false);
//构造一个ActivityClientRecord,将所有参数设置进去
//ActivityClientRecord是客户端Activity的信息记录类,对应AMS成员变量ActivityStackSupervisor维护的ActivityRecord信息记录类
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
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;
updatePendingConfiguration(curConfig);
//参数设置完毕,Handler发送LAUNCH_ACTIVITY消息-》1277行,handleLaunchActivity实例化Activity
sendMessage(H.LAUNCH_ACTIVITY, r);
}
public static void main(String[] args) {
SamplingProfilerIntegration.start();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
//为当前用户初始化环境参数
EventLogger.setReporter(new EventLoggingReporter());
Security.addProvider(new AndroidKeyStoreProvider());
//获取并确保信用凭证在目录中
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
//创建UI线程的Looper,也即主线线程的Looper,每个MessageQueue只会属于一个线程,而MessageQueue在Looper中
//Handler通过关联Looper来关联MessageQueue
1,Looper.prepareMainLooper();
//生成ActivityThread,ActivityThread并不是线程,是封装了UI线程消息循环与操作Activity生命周期的工具类,通过与AMS相互作用来进行管理
//创建ActivityThread
2,ActivityThread thread = new ActivityThread();
//false表示非系统应用调用,这里是创建Application和Activity,以及Instrumentation的入口
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
//用于调试
if (false) {
Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
}
//启动UI线程消息循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
此时main方法的循环和挂起,就是新应用程序所代表的主线程了。这里有两步工作最为重要,一是启动主线程的Looper循环;二是新建ActivityThread对对象,并调用attach方法。在创建ActivityThread时会初始化一个成员变量ApplicationThread 对象,前面我们反复见过许多次了,它继承ApplicationThreadNative 是一个Binder。
我们进入attach方法。
//向AMS发送启动完成消息
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
//不是系统进程
if (!system) {
ViewRootImpl.addFirstDrawHandler(new Runnable() {
@Override
public void run() {
ensureJitEnabled();
}
});
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//通过ActivityManagerNative获取到ActivityManagerService
final IActivityManager mgr = ActivityManagerNative.getDefault();
try {
//将ApplicationThread发送给AMS
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
// Ignore
}
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
mSomeActivitiesChanged = false;
try {
mgr.releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
}
}
}
});
} else {
......
}
attachApplication方法做了两个操作:一是跨进程通讯告知AMS,程序已经启动; 二是将ApplicationThread发送给AMS进行关联。
我们进入AMS来看下这个方法。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
//接收到ActivityThread创建成功的消息
@Override
public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
//从Binder获取调用方的进程pid
int callingPid = Binder.getCallingPid();
final long origId = Binder.clearCallingIdentity();
//根据pid启
attachApplicationLocked(thread, callingPid);
Binder.restoreCallingIdentity(origId);
}
}
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
//当前已经启动起来的进程
ProcessRecord app;
if (pid != MY_PID && pid >= 0) {
synchronized (mPidsSelfLocked) {
//根据pid取出ProcessRecord
app = mPidsSelfLocked.get(pid);
}
} else {
app = null;
}
if (app == null) {
if (pid > 0 && pid != MY_PID) {
Process.killProcessQuiet(pid);
} else {
try {
thread.scheduleExit();
} catch (Exception e) {
}
}
return false;
}
if (app.thread != null) {
handleAppDiedLocked(app, true, true);
}
//获取进程名
final String processName = app.processName;
try {
AppDeathRecipient adr = new AppDeathRecipient(
app, pid, thread);
thread.asBinder().linkToDeath(adr, 0);
app.deathRecipient = adr;
} catch (RemoteException e) {
app.resetPackageList(mProcessStats);
startProcessLocked(app, "link fail", processName);
return false;
}
//让ProcessRecord保存了ApplicationThread,AMS就可以通过ApplicationThread和ActivityThread通讯了
app.makeActive(thread, mProcessStats);
app.curAdj = app.setAdj = -100;
app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
app.forcingToForeground = null;
updateProcessForegroundLocked(app, false, false);
app.hasShownUi = false;
app.debugging = false;
app.cached = false;
//删除消息,因为进程在规定时间启动了
mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
......
ProfilerInfo profilerInfo = profileFile == null ? null
: new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop);
//ApplicationThread绑定Application
thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
mCoreSettingsObserver.getCoreSettingsLocked());
updateLruProcessLocked(app, false, null);
app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
} catch (Exception e) {
app.resetPackageList(mProcessStats);
app.unlinkDeathRecipient();
startProcessLocked(app, "bind fail", processName);
return false;
}
mPersistentStartingProcesses.remove(app);
mProcessesOnHold.remove(app);
boolean badApp = false;
boolean didSomething = false;
//正常启动Activity
if (normalMode) {
try {
//开始启动app
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
badApp = true;
}
}
......
return true;
}
这里分三步:
- 根据pid,找到当前进程的ProcessRecord对象,通过makeActive将ApplicationThread保存到了ProcessRecord中
- 调用ApplicationThread的bindApplication方法,绑定Application
- attachApplicationLocked从栈顶取出Activity进行启动
我们下面对应一步步分析,首先是makeActive方法。
final class ProcessRecord {
IApplicationThread thread;
......
public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
//thread为null
if (thread == null) {
final ProcessStats.ProcessState origBase = baseProcessTracker;
if (origBase != null) {
origBase.setState(ProcessStats.STATE_NOTHING,
tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
origBase.makeInactive();
}
baseProcessTracker = tracker.getProcessStateLocked(info.packageName, info.uid,
info.versionCode, processName);
baseProcessTracker.makeActive();
for (int i=0; i<pkgList.size(); i++) {
ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
if (holder.state != null && holder.state != origBase) {
holder.state.makeInactive();
}
holder.state = tracker.getProcessStateLocked(pkgList.keyAt(i), info.uid,
info.versionCode, processName);
if (holder.state != baseProcessTracker) {
holder.state.makeActive();
}
}
}
//保存到成员变量中
thread = _thread;
}
很简单,此时thread不为null,则将IApplicationThread 赋值了给了进程描述类ProcessRecord的成员变量thread。接着分析
ApplicationThread的bindApplication方法。
private class ApplicationThread extends ApplicationThreadNative {
......
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableOpenGlTrace, boolean isRestrictedBackupMode, boolean persistent,
Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services,
Bundle 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.enableOpenGlTrace = enableOpenGlTrace;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
//向Handler发送绑定消息
sendMessage(H.BIND_APPLICATION, data);
}
private class H extends Handler {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
//绑定Application,构建Instrumentation
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
}
private void handleBindApplication(AppBindData data) {
......
if (data.instrumentationName != null) {
......
} else {
//构建Instrumentation对象
mInstrumentation = new Instrumentation();
}
if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
}
final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
try {
//构建Application
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
if (!data.restrictedBackupMode) {
List<ProviderInfo> providers = data.providers;
if (providers != null) {
installContentProviders(app, providers);
mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
}
}
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}
catch (Exception e) {
throw new RuntimeException(
"Exception thrown in onCreate() of "
+ data.instrumentationName + ": " + e.toString(), e);
}
try {
//调用Application的onCreate
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
} finally {
StrictMode.setThreadPolicy(savedPolicy);
}
}
构建了Instrumentation对象,并回调了Application的onCreate方法。
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
此时,常见应用程序Application 的onCreate就被调用了。我们再来看最后一步,即mStackSupervisor.attachApplicationLocked从栈顶取出Activity进行启动。
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
//取出ActivityStack列表
ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
//倒序遍历,取出当前的ActivityStack
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = stacks.get(stackNdx);
if (!isFrontStack(stack)) {
continue;
}
//从ActivityStack栈顶取出ActivityRecord
ActivityRecord hr = stack.topRunningActivityLocked(null);
if (hr != null) {
if (hr.app == null && app.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
//正式启动Activity
if (realStartActivityLocked(hr, app, true, true)) {
didSomething = true;
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting activity "
+ hr.intent.getComponent().flattenToShortString(), e);
throw e;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0);
}
return didSomething;
}
mActivityDisplays列表保存了当前所有ActivityStack,因此,先从mActivityDisplays中取出当前的ActivityStack,再从ActivityStack栈中取出要启动的ActivityRecord,调用realStartActivityLocked进行开启。
final boolean realStartActivityLocked(ActivityRecord r,ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException {
//冻结未启动的其他Activity
r.startFreezingScreenLocked(app, 0);
//向WindowManager设置Token,标识当前App要位于前台显示
mWindowManager.setAppVisibility(r.appToken, true);
//搜索启动较慢的App的信息
r.startLaunchTickingLocked();
//检查配置信息
if (checkConfig) {
Configuration config = mWindowManager.updateOrientationFromAppTokens(
mService.mConfiguration,
r.mayFreezeScreenLocked(app) ? r.appToken : null);
mService.updateConfigurationLocked(config, r, false, false);
}
//记录了当前Activity在哪个进程上运行的
r.app = app;
app.waitingToKill = null;
r.launchCount++;
r.lastLaunchTime = SystemClock.uptimeMillis();
if (localLOGV) Slog.v(TAG, "Launching: " + r);
int idx = app.activities.indexOf(r);
//将Activity将入到进程维护的activity列表中
if (idx < 0) {
app.activities.add(r);
}
mService.updateLruProcessLocked(app, true, null);
mService.updateOomAdjLocked();
final ActivityStack stack = r.task.stack;
try {
if (app.thread == null) {
throw new RemoteException();
}
List<ResultInfo> results = null;
List<Intent> newIntents = null;
//是否调用onResume,上面传入了ture
if (andResume) {
results = r.results;
newIntents = r.newIntents;
}
if (andResume) {
EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
r.userId, System.identityHashCode(r),
r.task.taskId, r.shortComponentName);
}
//是否桌面Activity,如果是,添加到Activity栈底部
if (r.isHomeActivity() && r.isNotResolverActivity()) {
mService.mHomeProcess = r.task.mActivities.get(0).app;
}
mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
r.sleeping = false;
r.forceNewConfig = false;
mService.showAskCompatModeDialogLocked(r);
r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
String profileFile = null;
ParcelFileDescriptor profileFd = null;
if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
if (mService.mProfileProc == null || mService.mProfileProc == app) {
mService.mProfileProc = app;
profileFile = mService.mProfileFile;
profileFd = mService.mProfileFd;
}
}
app.hasShownUi = true;
app.pendingUiClean = true;
if (profileFd != null) {
try {
profileFd = profileFd.dup();
} catch (IOException e) {
if (profileFd != null) {
try {
profileFd.close();
} catch (IOException o) {
}
profileFd = null;
}
}
}
ProfilerInfo profilerInfo = profileFile != null
? new ProfilerInfo(profileFile, profileFd, mService.mSamplingInterval,
mService.mAutoStopProfiler) : null;
app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_TOP);
//ActivityThread启动Acitivity
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
results, newIntents, !andResume, mService.isNextTransitionForward(),
profilerInfo);
......
经过上面的赋值操作,再通过ActivityThread的内部类ApplicationThread调用scheduleLaunchActivity,设置所有参数,调用Handler发送消息调用handleLaunchActivity方法。
private class ApplicationThread extends ApplicationThreadNative {
......
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
IVoiceInteractor voiceInteractor, int procState, Bundle state,
PersistableBundle persistentState, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
ProfilerInfo profilerInfo) {
updateProcessState(procState, false);
//构造一个ActivityClientRecord,将所有参数设置进去
//ActivityClientRecord是客户端Activity的信息记录类,对应AMS成员变量ActivityStackSupervisor维护的ActivityRecord信息记录类
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
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;
updatePendingConfiguration(curConfig);
//参数设置完毕,Handler发送LAUNCH_ACTIVITY消息-》1277行,handleLaunchActivity实例化Activity
sendMessage(H.LAUNCH_ACTIVITY, r);
}
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
//开启Activity
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
//强转成ActivityClientRecord对象
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
//LoadedApk描述了一个已加载的apk对象,因为启动页面需要加载一些资源,资源都在apk里
//根据信息,获得一个LoadedApk对象,保存到packageInfo
r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
//通过反射实例化Activity
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
......
}
......
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
handleConfigurationChanged(null, null);
//反射生成Activity,调用了onCreate()
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
//调用onResume,并开始DecorView的渲染过程
handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed);
......
} else {
//创建Activity失败
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
} catch (RemoteException ex) {
// Ignore
}
}
}
每个应用程序都打包在一个apk文件中,在启动一个Activity时,需要将apk加载进来,ActivityThread内部使用一个LoadedApk对象来描述一个已加载的apk。而前面说过,ActivityClientRecord对象r则记录了一个Activity的信息,通过它调用handleLaunchActivity来创建Activity。
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//获取ActivityInfo
ActivityInfo aInfo = r.activityInfo;
//上面获取LoadedApk对象失败的话,再获取一次
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
//获得Activity包名类名
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);
}
//开始反射构造Activity
Activity activity = null;
try {
//通过类加载器
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
//通过Instrumentation反射生成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对象,并调用attch方法
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//创建Activity的Context上下文
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
//1,将appContext,Application等对象保存到Activity的成员变量中,并且获取PhoneWindow保存到mWindow
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.voiceInteractor);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
//2,Instrumentation调用callActivityOnCreate,让Activity去调用OnCreate方法
activity.mCalled = false;
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;
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
if (r.isPersistable()) {
//如果state,即Bundle不为空,调用callActivityOnRestoreInstanceState恢复之前的状态
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) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onPostCreate()");
}
}
}
r.paused = true;
//以token为key,保存ActivityClientRecord到Activities管理列表中
//这个token是一个binder,指向了服务端的ActivityRecord
mActivities.put(r.token, r);
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to start activity " + component
+ ": " + e.toString(), e);
}
}
return activity;
}
performLaunchActivity通过反射创建了Activity,如果创建成功,则会调用其onCreate方法,我们通常在onCreate设置的setContentView(R.layout.activity_main)就会被执行到。但要知道,setContentView只是遍历整个View树,添加到DecorView中,还没有进行渲染,渲染步骤是在handleResumeActivity进行的,我们将在接下来的《Activity渲染过程》中分析。
我们看2个关键的地方: activity.attach和mInstrumentation.callActivityOnCreate。
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, IVoiceInteractor voiceInteractor) {
//保存context到ContextImpl
attachBaseContext(context);
mFragments.attachActivity(this, mContainer, null);
//得到PhoneWindow,每个Activity有且只有一个
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
mUiThread = Thread.currentThread();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
mApplication = application;
mIntent = intent;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
mLastNonConfigurationInstances = lastNonConfigurationInstances;
if (voiceInteractor != null) {
if (lastNonConfigurationInstances != null) {
mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
} else {
mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
Looper.myLooper());
}
}
//获取WMS保存到mWindow中
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
//WMS保存到成员变量mWindowManager
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;
}
Activity继承ContextThemeWrapper,ContextThemeWrapper继承ContextWrapper这些都是包装类,attachBaseContext方法最终将上文赋值给Context的实现类ContextImpl ,PolicyManager.makeNewWindow创建了Window的子类PhoneWindow,Window是抽象类,而PhoneWindow是其唯一子类,代码最后获取WMS的远程代理,保存到PhoneWindow和Activity的成员变量中。
WMS和AMS一样,在SystemServer中就启动了,读者可以对照分析AMS的启动进行分析。这里我们看PhoneWindow如何创建,它非常重要。
public final class PolicyManager {
private static final String POLICY_IMPL_CLASS_NAME =
"com.android.internal.policy.impl.Policy";
private static final IPolicy sPolicy;
static {
//反射构造Policy对象
try {
Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
sPolicy = (IPolicy)policyClass.newInstance();
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be loaded", ex);
} catch (InstantiationException ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(
POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);
}
}
private PolicyManager() {}
//创建phoneWindow对象
public static Window makeNewWindow(Context context) {
return sPolicy.makeNewWindow(context);
}
......
}
PolicyManager实际上是一个代理类,具体实现是通过Policy对象来执行。
public class Policy implements IPolicy {
......
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}
......
到此Activity就有了一个PhoneWindow对象了。我们再看mInstrumentation的callActivityOnCreate方法。
public class Instrumentation {
......
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
//调用Activity的performCreate
activity.performCreate(icicle);
postPerformCreate(activity);
}
......
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback {
......
final void performCreate(Bundle icicle) {
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
......
到此,Activity的启动过程就分析完毕。下一篇我们将从setContentView讲起,来分析设置的布局是如何被添加和渲染到手机屏幕的。
网友评论