Activity启动过程源码解析
tellmzw
8年前
<h2>背景</h2> <p>启动App内部的Activity,Android 6.0 系统</p> <h2>概要</h2> <ol> <li>系统会为每个App创建一个进程,系统进程和App进程之间通过Binder通信</li> <li>2个Binder接口 IActivityManager 和 IApplicationThread</li> <li>几个Binder相关的类<br> ActivityManagerService extends ActivityManagerNative<br> ActivityManagerNative extends Binder implements IActivityManager<br> (简称AMS)<br> ApplicationThread extends ApplicationThreadNative<br> ApplicationThreadNative extends Binder implements IApplicationThread<br> (简称AT)</li> <li>App进程通知AMS启动Activity-->进入系统进程处理,通知上一个Activity的AT进行pause-->进入App进程,pause完成后,通知AMS-->进入系统进程处理,通知App的AT进行scheduleLaunchActivity --> 进入App进程,创建Activity对象,调用Activity.onCreate()、onStart()、onResume(),通知AMS-->进入系统进程处理,通知上一个App的AT进行stop</li> </ol> <p><img src="https://simg.open-open.com/show/4c94f5f20807b28635e42e1387c8b2f9.png"></p> <h2>详细</h2> <p>----------App进程----------></p> <p>1) Activity.startActivity()-->startActivityForResult()</p> <pre> <code class="language-java">public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) { ... Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); }</code></pre> <p>注意第二个参数 mMainThread.getApplicationThread()</p> <pre> <code class="language-java">public final class ActivityThread { final ApplicationThread mAppThread = new ApplicationThread(); public ApplicationThread getApplicationThread(){ return mAppThread; } }</code></pre> <p>mMainThread就是ActivityThread,持续跟踪 mMainThread.mAppThread</p> <p>2) Instrumentation.execStartActivity()</p> <pre> <code class="language-java">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; }</code></pre> <p>继续跟踪 mMainThread.mAppThread,whoThread就是它</p> <p>3) ActivityManagerNative.getDefault().startActivity()</p> <pre> <code class="language-java">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; } } }</code></pre> <p><img src="https://simg.open-open.com/show/d9bc202610d2a52e65a6be8e0750383a.png"></p> <p>继续跟踪 mMainThread.mAppThread,caller就是它,被传到 mRemote 的方法里了</p> <p>App进程通知系统进程都是通过ActivityManagerNative</p> <p>----------系统进程----------></p> <p>4) ActivityManagerService.startActivity()</p> <pre> <code class="language-java">@Override public final int startActivity(...) { return startActivityAsUser(...); } @Override public final int startActivityAsUser(...) { ... return mStackSupervisor.startActivityMayWait(...); }</code></pre> <p>5) ActivityStackSupervisor.startActivityMayWait()</p> <p>加工将要启动的Activity的相关信息</p> <p>6) ActivityStack.startPausingLocked()</p> <p>在 launchActivity 之前先pause上一个Activity,prev.app 表明不仅限于当前APP</p> <p><img src="https://simg.open-open.com/show/41e8fda16e8f5bb3ee530d68ae41a0d3.png"></p> <p>7) ActivityStackSupervisor.realStartActivityLocked()</p> <pre> <code class="language-java">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; }</code></pre> <p>上面跟踪App进程里的 mMainThread.mAppThread 那么久,终于在这里再现身影,app.thread 就是它的Binder接口</p> <p>系统进程通知App进程都是通过ApplicationThreadNative</p> <p>红框标示 ActivityManagerService.activityPaused() 说明App进程pause activity完成了</p> <p><img src="https://simg.open-open.com/show/743c092fc25d933a532e45b06daa6a4f.png"></p> <p>8) ApplicationThreadNative.scheduleLaunchActivity()</p> <pre> <code class="language-java">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); ... } } }</code></pre> <p>----------App进程----------></p> <p>9) ApplicationThreadNative</p> <pre> <code class="language-java">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); } } }</code></pre> <p>10) ActivityThread.ApplicationThread.scheduleLaunchActivity()</p> <pre> <code class="language-java">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); } }</code></pre> <p>mH是什么</p> <p>11) ActivityThread.H</p> <pre> <code class="language-java">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; ... ... } } }</code></pre> <p>看到这里,可以知道</p> <p>管理Activity都是通过Handler.sendMessage()</p> <p>要知道Handler都是和Looper配对使用的,新建Handler前,都需要初始化Looper,那Looper在哪</p> <p>12) ActivityThread.main()</p> <pre> <code class="language-java">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"); }</code></pre> <p>重点是这三句</p> <pre> <code class="language-java">Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); //内部 H mH = new H(); Looper.loop();</code></pre> <p>如果不清楚Handler和Looper可以参考Handler和Looper解析</p> <p>第一次启动App的时候,App还没有自己的进程,系统会创建一个新的进程,新的进程会导入android.app.ActivityThread,并且执行main()</p> <p>main()方法里Looper.loop()死循环取消息(管理Activity、Service...的消息),其他线程传输消息到main线程都是通过ActivityThread.mH.sendMessage()</p> <p>13) 回到 10) 里面的 sendMessage(H.LAUNCH_ACTIVITY, r)</p> <p>--> 11) 里面的 handleLaunchActivity(r, null)</p> <pre> <code class="language-java">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; }</code></pre> <p>mInstrumentation.callActivityOnCreate()-->activity.performCreate()-->onCreate()</p> <p>handleLaunchActivity()内部先执行performLaunchActivity()再执行handleResumeActivity()</p> <p>performLaunchActivity()内部会先执行mInstrumentation.callActivityOnCreate()再执行activity.performStart()</p> <p>至此,Activity执行了onCreate()-->onStart()-->onResume(),在App内部启动完毕。</p> <p>14) handleResumeActivity()</p> <pre> <code class="language-java">final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume) { ... ActivityClientRecord r = performResumeActivity(token, clearHide); ... try { ActivityManagerNative.getDefault().activityResumed(token); } catch (RemoteException ex) { } ... }</code></pre> <p>执行完onResume()通知AMS,系统进程就会接着去stop上一个Activity</p> <h3>总结</h3> <p>从上面的时序图也可以观察到</p> <ol> <li>Activity要通知系统进程,总是<br> Activity-->Instrumentation-->ActivityManagerNative--><br> 进入系统进程<br> ActivityManagerNative-->ActivityManagerService-->ActivityStackSupervisor/ActivityStack</li> <li>系统进程要管理Activity,总是<br> ApplicationThreadNative--><br> 进入App进程<br> ApplicationThreadNative-->ActivityThread.ApplicationThread-->ActivityThread.H-->Instrumentation-->Activity</li> <li>Activity A 启动 Activity B<br> 生命周期相关的整个过程是:a.onPause()-->b.onCreate()-->b.onStart()-->b.onResume()-->a.onStop()</li> </ol> <h3>如何debug SDK源码</h3> <ol> <li>使用模拟器,选Nexus系列</li> <li>下载源码 <p><img src="https://simg.open-open.com/show/914d20245c3fa4ecda3c74d44b86790a.png"></p> </li> <li>勾选Show all processes <p><img src="https://simg.open-open.com/show/28497c802fb0230913f1eb4211446bb2.png"></p> </li> <li>选择system_process <p><img src="https://simg.open-open.com/show/d8dfb215d4238b4864472b912c47e19a.png"></p> </li> <li>OK</li> </ol> <p> </p> <p>来自:http://www.jianshu.com/p/d4cc363813a7</p> <p> </p>