背景
啟動(dòng)App內(nèi)部的Activity,Android 6.0 系統(tǒng)
概要
- 系統(tǒng)會(huì)為每個(gè)App創(chuàng)建一個(gè)進(jìn)程,系統(tǒng)進(jìn)程和App進(jìn)程之間通過(guò)Binder通信
- 2個(gè)Binder接口 IActivityManager 和 IApplicationThread
- 幾個(gè)Binder相關(guān)的類(lèi)
ActivityManagerService extends ActivityManagerNative
ActivityManagerNative extends Binder implements IActivityManager
ActivityThread.ApplicationThread extends ApplicationThreadNative
ApplicationThreadNative extends Binder implements IApplicationThread - App進(jìn)程通知AMS啟動(dòng)Activity-->進(jìn)入系統(tǒng)進(jìn)程處理,通知上一個(gè)Activity的ApplicationThread進(jìn)行pause-->進(jìn)入App進(jìn)程凄诞,pause完成后驶俊,通知AMS-->進(jìn)入系統(tǒng)進(jìn)程處理桑滩,通知App的ApplicationThread進(jìn)行scheduleLaunchActivity --> 進(jìn)入App進(jìn)程剥汤,創(chuàng)建Activity對(duì)象颠放,調(diào)用Activity.onCreate()、onStart()吭敢、onResume()碰凶,通知AMS-->進(jìn)入系統(tǒng)進(jìn)程處理,通知上一個(gè)App的ApplicationThread進(jìn)行stop
詳細(xì)
----------App進(jìn)程---------->
- Activity.startActivity()-->startActivityForResult()
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
...
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
}
注意第二個(gè)參數(shù) mMainThread.getApplicationThread()
public final class ActivityThread {
final ApplicationThread mAppThread = new ApplicationThread();
public ApplicationThread getApplicationThread(){
return mAppThread;
}
}
mMainThread就是ActivityThread鹿驼,持續(xù)跟蹤 mMainThread.mAppThread
- Instrumentation.execStartActivity()
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
try {
...
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
...
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
繼續(xù)跟蹤 mMainThread.mAppThread欲低,whoThread就是它
- ActivityManagerNative.getDefault().startActivity()
public abstract class ActivityManagerNative extends Binder implements IActivityManager {
class ActivityManagerProxy implements IActivityManager
{
public ActivityManagerProxy(IBinder remote)
{
mRemote = remote;
}
public IBinder asBinder()
{
return mRemote;
}
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 {
...
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
...
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
...
return result;
}
}
}
繼續(xù)跟蹤 mMainThread.mAppThread,caller就是它畜晰,被傳到 mRemote 的方法里了
App進(jìn)程通知系統(tǒng)進(jìn)程都是通過(guò)ActivityManagerNative
----------系統(tǒng)進(jìn)程---------->
- ActivityManagerService.startActivity()
@Override
public final int startActivity(...) {
return startActivityAsUser(...);
}
@Override
public final int startActivityAsUser(...) {
...
return mStackSupervisor.startActivityMayWait(...);
}
ActivityStackSupervisor.startActivityMayWait()
加工將要啟動(dòng)的Activity的相關(guān)信息ActivityStack.startPausingLocked()
在 launchActivity 之前先pause上一個(gè)Activity伸头,prev.app 表明不僅限于當(dāng)前APP
- ActivityStackSupervisor.realStartActivityLocked()
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException {
...
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
...
} catch (RemoteException e) {
...
throw e;
}
...
return true;
}
上面跟蹤App進(jìn)程里的 mMainThread.mAppThread 那么久,終于在這里再現(xiàn)身影舷蟀,app.thread 就是它的Binder接口
系統(tǒng)進(jìn)程通知App進(jìn)程都是通過(guò)ApplicationThreadNative
紅框標(biāo)示 ActivityManagerService.activityPaused() 說(shuō)明App進(jìn)程pause activity完成了
- ApplicationThreadNative.scheduleLaunchActivity()
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {
class ApplicationThreadProxy implements IApplicationThread {
private final IBinder mRemote;
public final void scheduleLaunchActivity() throws RemoteException {
...
mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY);
...
}
}
}
----------App進(jìn)程---------->
- ApplicationThreadNative
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
...
case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION: {
...
}
case SCHEDULE_STOP_ACTIVITY_TRANSACTION: {
...
}
case SCHEDULE_RESUME_ACTIVITY_TRANSACTION: {
...
}
case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION: {
...
scheduleLaunchActivity(intent, b, ident, info, curConfig, overrideConfig, compatInfo,
referrer, voiceInteractor, procState, state, persistentState, ri, pi,
notResumed, isForward, profilerInfo);
return true;
}
case SCHEDULE_NEW_INTENT_TRANSACTION: {
...
}
case SCHEDULE_FINISH_ACTIVITY_TRANSACTION: {
...
}
case SCHEDULE_CREATE_SERVICE_TRANSACTION: {
...
}
case SCHEDULE_BIND_SERVICE_TRANSACTION: {
...
}
case SCHEDULE_UNBIND_SERVICE_TRANSACTION: {
...
}
...
return super.onTransact(code, data, reply, flags);
}
}
}
- ActivityThread.ApplicationThread.scheduleLaunchActivity()
public final class ActivityThread {
final ApplicationThread mAppThread = new ApplicationThread();
final H mH = new H();
private class ApplicationThread extends ApplicationThreadNative {
...
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
...
sendMessage(H.LAUNCH_ACTIVITY, r);
}
}
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;
...
mH.sendMessage(msg);
}
}
mH是什么
- ActivityThread.H
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
public static final int PAUSE_ACTIVITY = 101;
public static final int PAUSE_ACTIVITY_FINISHING= 102;
public static final int STOP_ACTIVITY_SHOW = 103;
public static final int STOP_ACTIVITY_HIDE = 104;
public static final int SHOW_WINDOW = 105;
public static final int HIDE_WINDOW = 106;
public static final int RESUME_ACTIVITY = 107;
public static final int SEND_RESULT = 108;
public static final int DESTROY_ACTIVITY = 109;
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int NEW_INTENT = 112;
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 UNBIND_SERVICE = 122;
public static final int DUMP_SERVICE = 123;
public static final int LOW_MEMORY = 124;
public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
public static final int RELAUNCH_ACTIVITY = 126;
public static final int PROFILER_CONTROL = 127;
public static final int CREATE_BACKUP_AGENT = 128;
public static final int DESTROY_BACKUP_AGENT = 129;
public static final int SUICIDE = 130;
public static final int REMOVE_PROVIDER = 131;
public static final int ENABLE_JIT = 132;
public static final int DISPATCH_PACKAGE_BROADCAST = 133;
public static final int SCHEDULE_CRASH = 134;
public static final int DUMP_HEAP = 135;
public static final int DUMP_ACTIVITY = 136;
public static final int SLEEPING = 137;
public static final int SET_CORE_SETTINGS = 138;
public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
public static final int TRIM_MEMORY = 140;
public static final int DUMP_PROVIDER = 141;
public static final int UNSTABLE_PROVIDER_DIED = 142;
public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
public static final int INSTALL_PROVIDER = 145;
public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
public static final int CANCEL_VISIBLE_BEHIND = 147;
public static final int BACKGROUND_VISIBLE_BEHIND_CHANGED = 148;
public static final int ENTER_ANIMATION_COMPLETE = 149;
public void handleMessage(Message msg) {
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
...
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;
case RESUME_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
handleResumeActivity((IBinder) msg.obj, true, msg.arg1 != 0, true);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...
...
}
}
}
看到這里恤磷,可以知道
管理Activity都是通過(guò)Handler.sendMessage()
要知道Handler都是和Looper配對(duì)使用的,新建Handler前野宜,都需要初始化Looper扫步,那Looper在哪
- ActivityThread.main()
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
AndroidKeyStoreProvider.install();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
重點(diǎn)是這三句
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread(); //內(nèi)部 H mH = new H();
Looper.loop();
如果不清楚Handler和Looper可以參考Handler和Looper解析
第一次啟動(dòng)App的時(shí)候,App還沒(méi)有自己的進(jìn)程匈子,系統(tǒng)會(huì)創(chuàng)建一個(gè)新的進(jìn)程河胎,新的進(jìn)程會(huì)導(dǎo)入android.app.ActivityThread,并且執(zhí)行main()
main()方法里L(fēng)ooper.loop()死循環(huán)取消息(管理Activity虎敦、Service...的消息)游岳,其他線(xiàn)程傳輸消息到main線(xiàn)程都是通過(guò)ActivityThread.mH.sendMessage()
- 回到 10) 里面的 sendMessage(H.LAUNCH_ACTIVITY, r)
--> 11) 里面的 handleLaunchActivity(r, null)
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
WindowManagerGlobal.initialize();
...
Activity a = performLaunchActivity(r, customIntent);
...
handleResumeActivity(r.token, false, r.isForward,!r.activity.mFinished && !r.startsNotResumed);
...
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
Activity activity = null;
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);//反射
...
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
...
return activity;
}
mInstrumentation.callActivityOnCreate()-->activity.performCreate()-->onCreate()
handleLaunchActivity()內(nèi)部先執(zhí)行performLaunchActivity()再執(zhí)行handleResumeActivity()
performLaunchActivity()內(nèi)部會(huì)先執(zhí)行mInstrumentation.callActivityOnCreate()再執(zhí)行activity.performStart()
至此,Activity執(zhí)行了onCreate()-->onStart()-->onResume()其徙,在App內(nèi)部啟動(dòng)完畢胚迫。
- handleResumeActivity()
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume) {
...
ActivityClientRecord r = performResumeActivity(token, clearHide);
...
try {
ActivityManagerNative.getDefault().activityResumed(token);
} catch (RemoteException ex) {
}
...
}
執(zhí)行完onResume()通知AMS,系統(tǒng)進(jìn)程就會(huì)接著去stop上一個(gè)Activity
總結(jié)
- Activity要通知系統(tǒng)進(jìn)程唾那,總是
Activity-->Instrumentation-->ActivityManagerNative-->
進(jìn)入系統(tǒng)進(jìn)程
ActivityManagerNative-->ActivityManagerService-->ActivityStackSupervisor/ActivityStack - 系統(tǒng)進(jìn)程要管理Activity访锻,總是
ApplicationThreadNative-->
進(jìn)入App進(jìn)程
ApplicationThreadNative-->ActivityThread.ApplicationThread-->ActivityThread.H-->Instrumentation-->Activity - Activity A 啟動(dòng) Activity B
生命周期相關(guān)的整個(gè)過(guò)程是:a.onPause()-->b.onCreate()-->b.onStart()-->b.onResume()-->a.onStop()
如何debug SDK源碼
- 使用模擬器,選Nexus系列
-
下載源碼
-
勾選Show all processes
-
選擇system_process
- OK