誰(shuí)啟動(dòng)了你的activity 颅筋?
首先拋出一個(gè)問(wèn)題寻定,當(dāng)你點(diǎn)擊桌面應(yīng)用圖標(biāo)的時(shí)候暴匠,你的Launch-Activity的oncreate方式是被誰(shuí)調(diào)用起來(lái)的,才會(huì)執(zhí)行到經(jīng)過(guò)了哪些流程才到Activity類(lèi)的oncreate方法里的房维?
要回答上面這個(gè)問(wèn)題首先需要了解到 應(yīng)用的啟動(dòng)流程沼瘫,app的啟動(dòng)流程大致可以同如下的流程概括- 當(dāng)前我們點(diǎn)擊launch中某個(gè)的app圖標(biāo)時(shí),Launcher進(jìn)程采用Binder IPC向system_server進(jìn)程發(fā)起startActivity請(qǐng)求
- 這個(gè)時(shí)候 system_server收到消息之后 就向zygote進(jìn)程發(fā)送fork一個(gè)子進(jìn)程的請(qǐng)求咙俩,這個(gè)進(jìn)程就是你的App進(jìn)程,
- App進(jìn)程耿戚,通過(guò)Binder IPC向sytem_server進(jìn)程發(fā)起attachApplication請(qǐng)求,
- system_server收到請(qǐng)求之后,進(jìn)行一系列準(zhǔn)備工作后就向App進(jìn)程發(fā)送了scheduledLaunch Activity的命令暴浦,
- App進(jìn)程的ApplicationThread收到消息后向ActivityThread 發(fā)送launchactivity的命令溅话,
- 主線(xiàn)程在收到Message后,通過(guò)發(fā)射機(jī)制創(chuàng)建目標(biāo)Activity歌焦,并回調(diào)Activity.onCreate()等方法。
所以主要啟動(dòng)工作都在A(yíng)ctivityThread.java 這個(gè)類(lèi)里面砚哆。
Activty Pause又是怎樣的流程 独撇?
首先要說(shuō)一下 Binder 和handler ,Bindle 是用于不同進(jìn)程間的通信使用躁锁,由一個(gè)binder的客戶(hù)端向另一個(gè)進(jìn)程的服務(wù)端發(fā)送請(qǐng)求纷铣;而handler是同一個(gè)進(jìn)程下面不同線(xiàn)程的通信,比如我們經(jīng)常用到的子線(xiàn)程向主線(xiàn)程通知更新ui都是通過(guò)handler的方式战转,看下圖- 當(dāng)我們的activty進(jìn)入后臺(tái)時(shí)線(xiàn)程1 ActivtyManagerService(具體Home進(jìn)入后臺(tái)是怎么通知到ActivtyManagerService的后面再研究)通過(guò)handler通知到線(xiàn)程2 ApplicationThreadProxy搜立,因?yàn)槭峭粋€(gè)進(jìn)程里面所以通過(guò)handler,
- ApplicationThreadProxy 通過(guò)binder方式將暫停activity消息通知到了線(xiàn)程4 ApplicationThread槐秧,
- 線(xiàn)程4通過(guò)handler消息機(jī)制啄踊,將暫停Activity的消息發(fā)送給主線(xiàn)程;
- 主線(xiàn)程在looper.loop()中循環(huán)遍歷消息刁标,當(dāng)收到暫停Activity的消息(PAUSE_ACTIVITY)時(shí)颠通,便將消息分發(fā)給ActivityThread.H.handleMessage()方法,再經(jīng)過(guò)方法的層層調(diào)用膀懈,最后便會(huì)調(diào)用到Activity.onPause()方法顿锰。
現(xiàn)在看看 android源碼里面是怎樣的
通過(guò)上面的流程圖我們知道 啟動(dòng) activty ,首先是ApplicationThreadProxy發(fā)送了Schedule LaunchActivity 消息启搂,ApplicationThread 是ActivityThread 的一個(gè)內(nèi)部類(lèi):
final ApplicationThread mAppThread = new ApplicationThread();
private class ApplicationThread extends ApplicationThreadNative {
private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
private int mLastProcessState = -1;
// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
@Override
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) {
updateProcessState(procState, false);
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.referrer = referrer;
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;
r.overrideConfig = overrideConfig;
updatePendingConfiguration(curConfig);
sendMessage(H.LAUNCH_ACTIVITY, r);
}
......
看到上面代碼 sendMessage(H.LAUNCH_ACTIVITY, r); 他發(fā)了消息出去 所以找實(shí)現(xiàn)handleMessage的地方:
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);
if (localLOGV) Slog.v(
TAG, "Handling launch of " + r);
// Initialize before creating the activity
WindowManagerGlobal.initialize();
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);
if (!r.activity.mFinished && r.startsNotResumed) {
// The activity manager actually wants this one to start out
// paused, because it needs to be visible but isn't in the
// foreground. We accomplish this by going through the
// normal startup (because activities expect to go through
// onResume() the first time they run, before their window
// is displayed), and then pausing it. However, in this case
// we do -not- need to do the full pause cycle (of freezing
// and such) because the activity manager assumes it can just
// retain the current state it has.
try {
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
// We need to keep around the original state, in case
// we need to be created again. But we only do this
// for pre-Honeycomb apps, which always save their state
// when pausing, so we can not have them save their state
// when restarting from a paused state. For HC and later,
// we want to (and can) let the state be saved as the normal
// part of stopping the activity.
if (r.isPreHoneycomb()) {
r.state = oldState;
}
if (!r.activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onPause()");
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to pause activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
r.paused = true;
}
} else {
// If there was an error, for any reason, tell the activity
// manager to stop us.
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
} catch (RemoteException ex) {
// Ignore
}
}
}
看到了 中間會(huì) handleConfigurationChanged 等配置硼控,(這個(gè)操作就對(duì)應(yīng)我們activty的 onConfigurationChanged():方法)然后就是 performLaunchActivity,在看看這個(gè)方法里面干了什么事胳赌,看它的返回值是個(gè)activity 牢撼,難道是解析manifest xml信息找到我們的launch的activity呢?繼續(xù)往下看吧匈织,
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
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 = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
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) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
if (localLOGV) Slog.v(
TAG, r + ": app=" + app
+ ", appName=" + app.getPackageName()
+ ", pkg=" + r.packageInfo.getPackageName()
+ ", comp=" + r.intent.getComponent().toShortString()
+ ", dir=" + r.packageInfo.getAppDir());
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
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()) {
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;
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;
}
從源碼里面看到了
activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent);
//下面還有 看到了,
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
上面這個(gè)地方獲取了activity實(shí)例浪默,我們先看看application的實(shí)例牡直,因?yàn)槲覀兠總€(gè)應(yīng)用都是有一個(gè)application的,先啟動(dòng)application再是activity才對(duì)的纳决,
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
得到了application 實(shí)例碰逸,
那么 application的oncreate在哪里調(diào)到的呢,我們進(jìn)到makeApplication 方法里面看下:
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader();
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
try {
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!instrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
}
// Rewrite the R 'constants' for all library apks.
SparseArray<String> packageIdentifiers = getAssets(mActivityThread)
.getAssignedPackageIdentifiers();
final int N = packageIdentifiers.size();
for (int i = 0; i < N; i++) {
final int id = packageIdentifiers.keyAt(i);
if (id == 0x01 || id == 0x7f) {
continue;
}
rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
}
return app;
}
看到有 instrumentation.callApplicationOnCreate(app); instrumentation 這個(gè)東東發(fā)起了 oncreate阔加,那我們進(jìn)去看下:
/**
* Perform calling of the application's {@link Application#onCreate}
* method. The default implementation simply calls through to that method.
*
* <p>Note: This method will be called immediately after {@link #onCreate(Bundle)}.
* Often instrumentation tests start their test thread in onCreate(); you
* need to be careful of races between these. (Well between it and
* everything else, but let's start here.)
*
* @param app The application being created.
*/
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
對(duì)沒(méi)錯(cuò)就是它啟動(dòng)了 application的oncreate饵史,這個(gè)app就是你自己的額application了,
然后在回到
mInstrumentation.callActivityOnCreate(activity, r.state);
繼續(xù)看下 callActivityOnCreate實(shí)現(xiàn)
/**
* Perform calling of an activity's {@link Activity#onCreate}
* method. The default implementation simply calls through to that method.
*
* @param activity The activity being created.
* @param icicle The previously frozen state (or null) to pass through to onCreate().
*/
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
然后就進(jìn)到了 Activity 里面了:
final void performCreate(Bundle icicle) {
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
之后 activity就調(diào)用了自己的onCreate胜榔。
哦胳喷,原來(lái)onCreate 是自己調(diào)用的,instrumentation 只是調(diào)用了performCreate而已夭织,所以以后要是有人問(wèn)你吭露,是誰(shuí)調(diào)用了 activty的onCreate,你就大聲的告訴他尊惰,是activity他自己讲竿。
所以是誰(shuí)啟動(dòng)了activity 那么你可以回到答是instrumentation 這個(gè)類(lèi),但是完成這個(gè)工作是在A(yíng)ctivityThread 這個(gè)線(xiàn)程里面來(lái)實(shí)現(xiàn)的弄屡。
不過(guò)ActivityThread 也是ApplicationThread 通過(guò)handler發(fā)消息給它题禀,它才知道執(zhí)行那個(gè)階段的流程,而ApplicationThread 是 ApplicationThreadProxy 通過(guò)binder消息得到的膀捷,而 ApplicationThreadProxy 是ActivityMangerService 告訴它的迈嘹,所以源頭應(yīng)該是ActivityMangerService 來(lái)控制。執(zhí)行oncreate還是onpause的全庸。
ActivityThread.handleLaunchActivity
->ActivityThread.handleConfigurationChanged
->ActivityThread.performConfigurationChanged
->ComponentCallbacks2.onConfigurationChanged
ActivityThread.performLaunchActivity
->LoadedApk.makeApplication
->Instrumentation.callApplicationOnCreate
->Application.onCreate
Instrumentation.callActivityOnCreate
->Activity.performCreate
->Activity.onCreate
Instrumentation.callActivityonRestoreInstanceState
->Activity.performRestoreInstanceState
->Activity.onRestoreInstanceState
ActivityThread.handleResumeActivity
->ActivityThread.performResumeActivity
->Activity.performResume
->Activity.performRestart
->Instrumentation.callActivityOnRestart
->Activity.onRestart
Activity.performStart
->Instrumentation.callActivityOnStart
->Activity.onStart
Instrumentation.callActivityOnResume
->Activity.onResume