上一篇我們已經發(fā)分析了Launcher啟動起來后,如何將應用程序封裝成桌面圖標,并設置了點擊事件監(jiān)聽的整個流程蔗崎。當點擊桌面圖標我擂,就會執(zhí)行Activity的startActivity方法衬以。
Activity的啟動分2種,即根Activity和子ACtivity校摩。根Activity的啟動就代表了一個應用程序的啟動過程看峻,子Activity有可能和啟動它們的Activity運行在同一個進程,也可能不同進程秧耗。這里需要注意的是备籽,我們以當前是在Launcher這個Activity中執(zhí)行跳轉,啟動新應用程序的根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用來監(jiān)控應用程序和系統之間的交互操作,系統要啟動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 {
//創(chuàng)建Instrumentation
mInstrumentation = new Instrumentation();
//創(chuàng)建Application上下文
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
//創(chuàng)建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。
這些關鍵點或衡,會再下面分析到焦影,我們繼續(xù)看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發(fā)送數據。
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();//執(zhí)行run
}
private void run() {
......
try {
//啟動服務捌臊,創(chuàng)建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);
}
......
這里使用了靜態(tài)代理模式刃泌,ActivityManagerProxy實現了IActivityManager凡壤。
class ActivityManagerProxy implements IActivityManager{
public ActivityManagerProxy(IBinder remote)
{
mRemote = remote;
}
public IBinder asBinder()
{
return mRemote;
}
//將數據發(fā)送給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發(fā)送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發(fā)送了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;
......
//創(chuàng)建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();
......
//執(zhí)行resume
if (doResume) {
//mStackSupervisor是管理stack的,最終由stack任務棧執(zhí)行resumeTopActivitiesLocked
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
此時為開啟新的任務棧匈仗,并將ActivityRecord 添加到新棧的最頂端瓢剿,由前面?zhèn)魅氲膁oResume知道,此時它的值為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執(zhí)行pause上一個activity的操作
result = resumeTopActivityInnerLocked(prev, options);
} finally {
inResumeTopActivity = false;
}
return result;
}
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
......
//獲取棧頂不是處于結束狀態(tài)的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;
}
......
//先執(zhí)行當前Activity的Pause何鸡,再執(zhí)行新的resume
boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
if (mResumedActivity != null) {
//執(zhí)行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執(zhí)行暫停操作迎膜,最終回調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發(fā)送一個通知,表示已暫停完畢劫恒,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)發(fā)送消息
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 收到暫停的通知,將消息發(fā)給Handler處理喧务。
private class H extends Handler {
......
//執(zhí)行上一個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,會執(zhí)行handlePauseActivity功茴,并調用我們常重寫的onPause()
performPauseActivity(token, finished, r.isPreHoneycomb());
if (r.isPreHoneycomb()) {
//3,先保存下數據
QueuedWork.waitToFinish();
}
//4孽亲,上面3件事執(zhí)行完成坎穿,通知AMS暫停已執(zhí)行完畢,可以開始下一個activity了
if (!dontReport) {
try {
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
}
}
mSomeActivitiesChanged = true;
}
}
ActivityThread被當成客戶端返劲,而每個Activity都用ActivityClientRecord來記錄信息玲昧,它對應了AMS的ActivityRecord。這個方法做了4件事:
- 向Launcher組件發(fā)送了一個用戶離開事件通知篮绿,即調用它的成員函數onUserLeaveHint孵延;
- 執(zhí)行我們熟悉的Activity生命周期方法onPause;
- 將數據進行保存亲配,當重新Resume時尘应,才能保證數據的恢復;
- 最后是向AMS發(fā)送通知吼虎,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()方法執(zhí)行
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了电湘,即執(zhí)行了AMS的activityPaused方法。
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
//棧執(zhí)行暫停鎖定,并開始下一個activity的啟動
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
前面說到如果AMS沒有在指定時間內收到消息寂呛,也會向Handler發(fā)送消息怎诫,來執(zhí)行這個方法,如下贷痪。
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);
}
//執(zhí)行暫停鎖定
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已經在規(guī)定事件發(fā)送消息給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狀態(tài)
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狀態(tài)
prev = null;
}
mPausingActivity = null;
}
if (resumeNext) {
//暫停完成舱沧,獲取頂層的ActivityStack
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
//系統是不是睡眠或關閉狀態(tài)
if (!mService.isSleepingOrShuttingDown()) {
//執(zhí)行resumeTopActivitiesLocked來開啟下一個Activity
mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
} else {
mStackSupervisor.checkReadyForSleepLocked();
ActivityRecord top = topStack.topRunningActivityLocked(null);
if (top == null || (prev != null && top != prev)) {
//執(zhí)行resumeTopActivitiesLocked來開啟下一個Activity
mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
}
}
}
......
}
將Launcher置為Pause狀態(tài)妹沙,以及將mPausingActivity置為null,隨后又回到調用resumeTopActivitiesLocked啟動位于棧頂的Activity熟吏,由于此時的mResumedActivity ==null距糖,因此最終會執(zhí)行到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,創(chuàng)建新的進程黎休,再啟動新的Activity唬渗,由于此處是啟動根Activity,因此應用程序的進程還沒創(chuàng)建奋渔,AMS會通知Zygote創(chuàng)建新的進程镊逝,走startProcessLocked方法。這個流程已經在《App桌面圖標顯示過程》一篇分析過嫉鲸。
AMS會設定一個時間來等待市咽,Zygote進程創(chuàng)建成功后會通知AMS澡刹,如果超時了,則AMS會認為創(chuàng)建失敗,不啟動新的Activity搓萧。創(chuàng)建成功蛀恩,最后調用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發(fā)送LAUNCH_ACTIVITY消息-》1277行微王,handleLaunchActivity實例化Activity
sendMessage(H.LAUNCH_ACTIVITY, r);
}
public static void main(String[] args) {
SamplingProfilerIntegration.start();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
//為當前用戶初始化環(huán)境參數
EventLogger.setReporter(new EventLoggingReporter());
Security.addProvider(new AndroidKeyStoreProvider());
//獲取并確保信用憑證在目錄中
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
//創(chuàng)建UI線程的Looper,也即主線線程的Looper,每個MessageQueue只會屬于一個線程品嚣,而MessageQueue在Looper中
//Handler通過關聯Looper來關聯MessageQueue
1炕倘,Looper.prepareMainLooper();
//生成ActivityThread,ActivityThread并不是線程翰撑,是封裝了UI線程消息循環(huán)與操作Activity生命周期的工具類罩旋,通過與AMS相互作用來進行管理
//創(chuàng)建ActivityThread
2,ActivityThread thread = new ActivityThread();
//false表示非系統應用調用眶诈,這里是創(chuàng)建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線程消息循環(huán)
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
此時main方法的循環(huán)和掛起涨醋,就是新應用程序所代表的主線程了。這里有兩步工作最為重要逝撬,一是啟動主線程的Looper循環(huán)浴骂;二是新建ActivityThread對對象,并調用attach方法球拦。在創(chuàng)建ActivityThread時會初始化一個成員變量ApplicationThread 對象,前面我們反復見過許多次了帐我,它繼承ApplicationThreadNative 是一個Binder坎炼。
我們進入attach方法。
//向AMS發(fā)送啟動完成消息
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發(fā)送給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發(fā)送給AMS進行關聯谣光。
我們進入AMS來看下這個方法。
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
//接收到ActivityThread創(chuàng)建成功的消息
@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;
//刪除消息萄金,因為進程在規(guī)定時間啟動了
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發(fā)送綁定消息
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逞带,上面?zhèn)魅肓藅ure
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發(fā)送消息調用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發(fā)送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 {
//創(chuàng)建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來創(chuàng)建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 {
//反射創(chuàng)建Application對象黄橘,并調用attch方法
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//創(chuàng)建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恢復之前的狀態(tài)
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通過反射創(chuàng)建了Activity椰于,如果創(chuàng)建成功怠益,則會調用其onCreate方法,我們通常在onCreate設置的setContentView(R.layout.activity_main)就會被執(zhí)行到瘾婿。但要知道蜻牢,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創(chuàng)建了Window的子類PhoneWindow灶轰,Window是抽象類谣沸,而PhoneWindow是其唯一子類,代碼最后獲取WMS的遠程代理框往,保存到PhoneWindow和Activity的成員變量中鳄抒。
WMS和AMS一樣闯捎,在SystemServer中就啟動了椰弊,讀者可以對照分析AMS的啟動進行分析。這里我們看PhoneWindow如何創(chuàng)建瓤鼻,它非常重要秉版。
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() {}
//創(chuàng)建phoneWindow對象
public static Window makeNewWindow(Context context) {
return sPolicy.makeNewWindow(context);
}
......
}
PolicyManager實際上是一個代理類,具體實現是通過Policy對象來執(zhí)行茬祷。
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講起,來分析設置的布局是如何被添加和渲染到手機屏幕的沃粗。