Activity是平常開發中最經常使用的組件,系統給咱們作了不少不少的封裝,讓咱們平時用起來特別簡單,很順暢.可是你有沒有想過,系統內部是如何啓動一個Activity的呢?Activity對象是如何建立的,又是如何回調生命週期方法的?經過對底層工做原理的學習,是通往高級工程師的必經之路,咱們必須對Activity的啓動原理知己知彼,才能在平時的開發中應對各類疑難雜症.本文主要是對Activity啓動流程的主要流程講解,目的是給咱們一個感性的認識,不用深扣代碼細節,便可對上層開發有指導意義.除非是ROM開發,那底層細節仍是須要注意.html
插播:ActivityManagerService(如下簡稱AMS)管理着四大組件的啓動、切換、調度及應用進程的管理和調度等工做,是Android中很是很是核心的服務.和AMS進行通訊是須要跨進程的.java
ps: 本文是以API 28爲例android
Instrumentation會在應用程序的任何代碼運行以前被實例化,它可以容許你監視應用程序和系統的全部交互.它還會構造Application,構建Activity,以及生命週期都會通過這個對象去執行.promise
Android核心服務,簡稱AMS,負責調度各應用進程,管理四大組件.實現了IActivityManager接口,應用進程能經過Binder機制調用系統服務.app
至關因而一個消息對象,當ActivityThread接收到這個消息則去啓動Activity.收到消息後執行execute方法啓動activity.async
應用的主線程.程序的入口.在main方法中開啓loop循環,不斷地接收消息,處理任務.ide
Launcher,也就是咱們熟悉的安卓桌面,它實際上是一個APP.只不過這個APP有點特殊,特殊在於它是系統開機後第一個啓動的APP,而且該APP常駐在系統中,不會被殺死,用戶一按home鍵就會回到桌面(回到該APP).桌面上面放了不少不少咱們本身安裝的或者是系統自帶的APP,咱們經過點擊這個應用的快捷方法能夠打開該應用.目前Android原生的Launcher版本是Launcher3.而下面提到的Launcher.java
是Launcher3中的一個Activity.該Activity中擺放着各應用的快捷方式圖標.oop
咱們經過點擊快捷方式,Launcher這個Activity的onClick方法會被調用源碼分析
public void onClick(View v) {
......
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
//點擊的是快捷方式->onClickAppShortcut
onClickAppShortcut(v);
}
.....
}
protected void onClickAppShortcut(final View v) {
....
// Start activities
startAppShortcutOrInfoActivity(v);
}
private void startAppShortcutOrInfoActivity(View v) {
//將啓動信息放在了點擊View的tag裏面
ItemInfo item = (ItemInfo) v.getTag();
// 應用程序安裝的時候根據 AndroidManifest.xml 由 PackageManagerService 解析並保存的
Intent intent;
if (item instanceof PromiseAppInfo) {
PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
intent = promiseAppInfo.getMarketIntent();
} else {
intent = item.getIntent();
}
boolean success = startActivitySafely(v, intent, item);
....
}
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
......
// Prepare intent
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
......
// Could be launching some bookkeeping activity
startActivity(intent, optsBundle);
......
}
複製代碼
在處理點擊事件時,通過onClickAppShortcut方法調用startAppShortcutOrInfoActivity方法,獲取Intent信息,而後調用startActivitySafely方法,在裏面調用了咱們常用的startActivity方法.由於Launcher類是一個Activity,因此調startActivity方法是理所固然的.這裏調用startActivity方法就會啓動APP的第一個Activity.post
以API 28的源碼爲例
來到Activity的startActivity方法,這個方法最終會調用startActivityForResult()
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
//mMainThread是ActivityThread,mMainThread.getApplicationThread()是獲取ApplicationThread
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
}
複製代碼
startActivityForResult裏面調用了Instrumentation的execStartActivity方法,其中mMainThread是ActivityThread(就是從這裏開始啓動一個應用的),mMainThread.getApplicationThread()是獲取ApplicationThread.ApplicationThread是ActivityThread的內部類,待會兒會介紹到.
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {
//1. 將ApplicationThread轉爲IApplicationThread
IApplicationThread whoThread = (IApplicationThread) contextThread;
//2. 獲取AMS實例,調用startActivity方法
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
return null;
}
複製代碼
IApplicationThread是一個Binder接口,它繼承自IInterface.ApplicationThread是繼承了IApplicationThread.Stub,實現了IApplicationThread的,因此能夠轉成IApplicationThread.
而後就是獲取AMS實例,調用AMS的startActivity方法.
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
//1. 獲取服務的Binder對象
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
//2. aidl 獲取AMS
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
複製代碼
ServiceManager是安卓中一個重要的類,用於管理全部的系統服務,維護着系統服務和客戶端的binder通訊。返回的是Binder對象,用來進行應用與系統服務之間的通訊的.
下面咱們繼續進入AMS的startActivity方法
@Override
public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
// TODO: Switch to user app stacks here.
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}
複製代碼
AMS的startActivity方法會調用AMS的startActivityAsUser方法,而後又調用另外一個startActivityAsUser方法.最後來了一串鏈式調用,最後會來到ActivityStarter的execute方法.
int execute() {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
}
private int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity, int userId, TaskRecord inTask, String reason, boolean allowPendingRemoteAnimationRegistryLookup) {
......
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
allowPendingRemoteAnimationRegistryLookup);
......
}
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, TaskRecord inTask, String reason, boolean allowPendingRemoteAnimationRegistryLookup) {
......
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
inTask, allowPendingRemoteAnimationRegistryLookup);
......
}
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
......
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
複製代碼
ActivityStarter的execute方法會繼續調用startActivityMayWait方法.startActivityMayWait會去調用startActivity方法,而後調用另外一個startActivity方法.而後又是調用另外一個startActivity方法,
不得不說,這些方法的參數可真是長啊,,,,多是因爲歷史緣由吧.
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity) {
......
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
......
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity) {
.......
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity, mOptions);
return START_SUCCESS;
}
複製代碼
終於不用調用startActivity方法了,調用startActivityUnchecked方法,在裏面調用了ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法
boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
......
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
......
}
複製代碼
targetStack是ActivityStack,會調用ActivityStack的resumeTopActivityUncheckedLocked方法,而後調用resumeTopActivityInnerLocked方法.
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
......
result = resumeTopActivityInnerLocked(prev, options);
.....
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
......
mStackSupervisor.startSpecificActivityLocked(next, true, false);
......
return true;
}
複製代碼
而後又會回到ActivityStackSupervisor的startSpecificActivityLocked方法
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
....
//進程存在則啓動
if (app != null && app.thread != null) {
realStartActivityLocked(r, app, andResume, checkConfig);
return;
}
//進程不存在則建立
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
複製代碼
這裏會判斷一下進程是否存在,若是不存在則建立一下.這裏的mService是AMS,會調用AMS的startProcessLocked方法.
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) {
return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
......
final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
......
}
private final boolean startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride) {
return startProcessLocked(app, hostingType, hostingNameStr,
false /* disableHiddenApiChecks */, abiOverride);
}
private final boolean startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
......
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);
......
}
private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint, ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal, String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) {
......
final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
requiredAbi, instructionSet, invokeWith, app.startTime);
......
}
private ProcessStartResult startProcess(String hostingType, String entryPoint, ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal, String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) {
......
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
......
}
複製代碼
這裏AMS調用了不少層startProcessLocked,最終都會調用startProcess方法,而後經過Process調用start方法.
public static final ProcessStartResult start(final String processClass, final String niceName, int uid, int gid, int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String[] zygoteArgs) {
return startViaZygote(processClass, niceName, uid, gid, gids,
debugFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, zygoteArgs);
}
private static ProcessStartResult startViaZygote(final String processClass, final String niceName, final int uid, final int gid, final int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String[] extraArgs) throws ZygoteStartFailedEx {
......
//若是須要,則打開Socket,用來和zygote通信
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
}
private static Process.ProcessStartResult zygoteSendArgsAndGetResult( ZygoteState zygoteState, ArrayList<String> args) throws ZygoteStartFailedEx {
......
final BufferedWriter writer = zygoteState.writer;
final DataInputStream inputStream = zygoteState.inputStream;
writer.write(Integer.toString(args.size()));
writer.newLine();
for (int i = 0; i < sz; i++) {
String arg = args.get(i);
writer.write(arg);
writer.newLine();
}
writer.flush();
// Should there be a timeout on this?
Process.ProcessStartResult result = new Process.ProcessStartResult();
// Always read the entire result from the input stream to avoid leaving
// bytes in the stream for future process starts to accidentally stumble
// upon.
result.pid = inputStream.readInt();
result.usingWrapper = inputStream.readBoolean();
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
return result;
......
}
複製代碼
上一步拿到了zygoteState 如今進行通信,首先經過一個一個參數write方法傳輸過去給zygote.zygote拿到這些參數就會給你建立好須要的進程.而後返回結果經過read讀取出來。這裏建立的進程就是APP的進程.zygote經過fork出子進程.
進程的入口,也就是被咱們熟知的ActivityThread的main方法,這個方法思路異常清晰,很是簡潔.固然,這裏也是主線程的入口.
public static void main(String[] args) {
//分析1 主線程Looper安排上
Looper.prepareMainLooper();
......
//分析2
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
//分析3 死循環,接收主線程上的消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
複製代碼
其中分析1和分析3在死磕Android_Handler機制你須要知道的一切已進行詳細的描述講解,這裏再也不贅述.
咱們來分析一下第2點:
final ApplicationThread mAppThread = new ApplicationThread();
private void attach(boolean system, long startSeq) {
......
if (!system) {
//這一步是獲取AMS實例,上面已經出現過
final IActivityManager mgr = ActivityManager.getService();
//而後跨進程通訊
mgr.attachApplication(mAppThread, startSeq);
}
}
複製代碼
經過獲取AMS,進行跨進程通訊,調用AMS的attachApplication方法
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
@GuardedBy("this")
private final boolean attachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq) {
......
//這裏的thread就是ActivityThread中的ApplicationThread
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
// See if the top visible activity is waiting to run in this process...
//看一下是否是有須要運行的Activity
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
......
return true;
}
複製代碼
這裏有2個須要注意的點
咱們先來看ApplicationThread的bindApplication方法
public final void bindApplication(String processName, ApplicationInfo appInfo, List<ProviderInfo> providers, ComponentName instrumentationName, ProfilerInfo profilerInfo, Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher, IUiAutomationConnection instrumentationUiConnection, int debugMode, boolean enableBinderTracking, boolean trackAllocation, boolean isRestrictedBackupMode, boolean persistent, Configuration config, CompatibilityInfo compatInfo, Map services, Bundle coreSettings, String buildSerial, boolean autofillCompatibilityEnabled) {
AppBindData data = new AppBindData();
.......
//主要就是發送一個消息
sendMessage(H.BIND_APPLICATION, data);
}
void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
//mH是一個Handler,發送了一個消息
mH.sendMessage(msg);
}
class H extends Handler {
//先看看這個Handler的部分消息名稱,一看就知道是幹嗎的,什麼綁定Application,綁定Service,中止Service什麼的.這個Handler和這些組件的啓動中止什麼的,關係很是大.
//其實這個Handler在API 28以前的時候消息更多,(API 28只是融合了一下,多個消息變成1個消息,仍是會走到這個Handler),以前Activity的各類生命週期回調都有對應的消息名稱裏.如今是融合了.
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int RECEIVER = 113;
public static final int CREATE_SERVICE = 114;
public static final int SERVICE_ARGS = 115;
public static final int STOP_SERVICE = 116;
public static final int CONFIGURATION_CHANGED = 118;
public static final int CLEAN_UP_CONTEXT = 119;
public static final int GC_WHEN_IDLE = 120;
public static final int BIND_SERVICE = 121;
public static final int RELAUNCH_ACTIVITY = 160;
}
複製代碼
在ApplicationThread的bindApplication中會調用sendMessage(該方法是ActivityThread中的,由於ApplicationThread是內部類,因此能夠調用)方法發送一條消息,經過H(這個類是ActivityThread的內部類)這個Handler進行接收消息.由於ApplicationThread是運行在Binder線程池中,因此須要切換到主線程中進行一些UI上的操做,好比開啓Activity什麼的.最後會來到H的BIND_APPLICATION消息處
public void handleMessage(Message msg) {
switch (msg.what) {
case BIND_APPLICATION:
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
break;
......
}
}
private void handleBindApplication(AppBindData data) {
// Continue loading instrumentation.
if (ii != null) {
ApplicationInfo instrApp;
instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
UserHandle.myUserId());
//構建ContextImpl
final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
//獲取其classLoader
final ClassLoader cl = instrContext.getClassLoader();
//構建Instrumentation
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();
} else {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
}
Application app;
// If the app is being launched for full backup or restore, bring it up in
// a restricted environment with the base application class.
//構建Application
app = data.info.makeApplication(data.restrictedBackupMode, null);
//調用Application的onCreate方法
mInstrumentation.callApplicationOnCreate(app);
}
//sources/android-28/android/app/LoadedApk.java#makeApplication
public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
//注意,若是Application已經初始化,那麼就不從新初始化了
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
//構建Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
return app;
}
//sources/android-28/android/app/Instrumentation.java#newApplication
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
//經過反射構建Application
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
//賦值Context
app.attach(context);
return app;
}
public @NonNull Application instantiateApplication(@NonNull ClassLoader cl, @NonNull String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (Application) cl.loadClass(className).newInstance();
}
複製代碼
在H這個Handler中處理BIND_APPLICATION這個消息,首先是經過ClassLoader加載構建Instrumentation對象,而後經過LoadedApk調用Instrumentation的newApplication 方法(這裏有點奇怪,爲何不用構建出來的mInstrumentation直接調用newApplication方法..),經過loadClass的方式將Application對象建立出來,而後調用Application的onCreate生命週期方法.
下面咱們繼續ActivityStackSupervisor的attachApplicationLocked方法
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
......
realStartActivityLocked(activity, app,top == activity, true);
......
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException {
......
// Create activity launch transaction.
//建立活動啓動事務。
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
//構建LaunchActivityItem對象,並傳入clientTransaction中,用做callback
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Schedule transaction.
//執行事務 這裏getLifecycleManager獲取的是ClientLifecycleManager
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
......
}
//ClientLifecycleManager#scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//繼續深刻
transaction.schedule();
}
//ClientTransaction#schedule
public void schedule() throws RemoteException {
//這裏的mClient是ApplicationThread
mClient.scheduleTransaction(this);
}
//ApplicationThread#scheduleTransaction
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//ActivityThread是繼承自ClientTransactionHandler的,scheduleTransaction方法在ClientTransactionHandler裏面
ActivityThread.this.scheduleTransaction(transaction);
}
//ClientTransactionHandler#scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
//注意啦,這裏向ActivityThread裏面的H這個Handler發送了一個EXECUTE_TRANSACTION的消息,而且將ClientTransaction對象也傳了進去
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//ClientTransactionHandler#sendMessage 這個方法是抽象方法,是在ActivityThread裏面實現的,固然是給H這個Handler發消息啦
abstract void sendMessage(int what, Object obj);
複製代碼
在Android8.0中,是經過ApplicationThread.scheduleLaunchActivity()對相關數據進行封裝,而後經過調用ActivityThread類的sendMessage()發送出去。 可是在Android9.0中,引入了ClientLifecycleManager和ClientTransactionHandler來輔助管理Activity生命週期。 至關於將生命週期抽象了出來,一個生命週期取而代之的是一個對象.
經過上面方法調用的展轉反側,最後來到了ClientTransactionHandler的scheduleTransaction方法,而後向ActivityThread的H發送了一個EXECUTE_TRANSACTION
消息. 在API 28裏面,ActivityThread的H這個Handler裏面已經沒了以前的那些什麼LAUNCH_ACTIVITY
、PAUSE_ACTIVITY
、RESUME_ACTIVITY
這些消息了,取而代之的是EXECUTE_TRANSACTION
這一個消息.
//ActivityThread裏面的H
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this); //這裏傳入的是ClientTransactionHandler對象(即ActivityThread),ClientTransactionHandler是ActivityThread的父類
class H extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case EXECUTE_TRANSACTION:
//首先取出ClientTransaction對象
final ClientTransaction transaction = (ClientTransaction) msg.obj;
//將ClientTransaction傳入execute方法
mTransactionExecutor.execute(transaction);
}
}
}
//TransactionExecutor#execute
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
//TransactionExecutor#executeCallbacks
public void executeCallbacks(ClientTransaction transaction) {
//取出ClientTransaction對象裏面的callback,即上面的LaunchActivityItem
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
}
}
//LaunchActivityItem#execute
@Override
public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
//調用ActivityThread的handleLaunchActivity方法
client.handleLaunchActivity(r, pendingActions, null);
}
複製代碼
在ActivityThread中的EXECUTE_TRANSACTION
消息中,執行了TransactionExecutor對象的execute方法,而後在裏面咱們執行了executeCallbacks方法.在executeCallbacks方法裏面拿出ClientTransaction對象的callback,即上面存進去的LaunchActivityItem. 再執行LaunchActivityItem的execute方法,調用的是ActivityThread的handleLaunchActivity方法,終於來到了咱們熟悉的環節.
//ActivityThread#handleLaunchActivity
@Override
public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {
.....
//終於要開始調用performLaunchActivity這個熟悉的方法了
final Activity a = performLaunchActivity(r, customIntent);
......
}
//ActivityThread#performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//獲取ClassLoader
java.lang.ClassLoader cl = appContext.getClassLoader();
//經過(Activity) cl.loadClass(className).newInstance()建立
//重點來啦:Activity是在ActivityThread的performLaunchActivity方法中用ClassLoader類加載器建立出來的。
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
//底層也是經過反射構建Application,若是已經構建則不會重複構建,畢竟一個進程只能有一個Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
Window window = null;
appContext.setOuterContext(activity);
//在這裏實例化了PhoneWindow,並將該Activity設置爲PhoneWindow的Callback回調,還初始化了WindowManager
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback);
//間接調用了Activity的performCreate方法,間接調用了Activity的onCreate方法.
mInstrumentation.callActivityOnCreate(activity, r.state);
//這裏和上面onCreate過程差很少,調用Activity的onStart方法
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
....
}
return activity;
}
複製代碼
這個流程就比較熟悉了,重點是:** Activity是在ActivityThread的performLaunchActivity方法中用ClassLoader類加載器建立出來的。** 建立出來以後就會調用Activity的onCreate方法和onStart方法.
關於後面的Activity建立出來以後的View的繪製,請看這裏