谁启动了你的activity ?
首先抛出一个问题,当你点击桌面应用图标的时候,你的Launch-Activity的oncreate方式是被谁调用起来的,才会执行到经过了哪些流程才到Activity类的oncreate方法里的?
要回答上面这个问题首先需要了解到 应用的启动流程,app的启动流程大致可以同如下的流程概括- 当前我们点击launch中某个的app图标时,Launcher进程采用Binder IPC向system_server进程发起startActivity请求
- 这个时候 system_server收到消息之后 就向zygote进程发送fork一个子进程的请求,这个进程就是你的App进程,
- App进程,通过Binder IPC向sytem_server进程发起attachApplication请求,
- system_server收到请求之后,进行一系列准备工作后就向App进程发送了scheduledLaunch Activity的命令,
- App进程的ApplicationThread收到消息后向ActivityThread 发送launchactivity的命令,
- 主线程在收到Message后,通过发射机制创建目标Activity,并回调Activity.onCreate()等方法。
所以主要启动工作都在ActivityThread.java 这个类里面。
Activty Pause又是怎样的流程 ?
首先要说一下 Binder 和handler ,Bindle 是用于不同进程间的通信使用,由一个binder的客户端向另一个进程的服务端发送请求;而handler是同一个进程下面不同线程的通信,比如我们经常用到的子线程向主线程通知更新ui都是通过handler的方式,看下图- 当我们的activty进入后台时线程1 ActivtyManagerService(具体Home进入后台是怎么通知到ActivtyManagerService的后面再研究)通过handler通知到线程2 ApplicationThreadProxy,因为是同一个进程里面所以通过handler,
- ApplicationThreadProxy 通过binder方式将暂停activity消息通知到了线程4 ApplicationThread,
- 线程4通过handler消息机制,将暂停Activity的消息发送给主线程;
- 主线程在looper.loop()中循环遍历消息,当收到暂停Activity的消息(PAUSE_ACTIVITY)时,便将消息分发给ActivityThread.H.handleMessage()方法,再经过方法的层层调用,最后便会调用到Activity.onPause()方法。
现在看看 android源码里面是怎样的
通过上面的流程图我们知道 启动 activty ,首先是ApplicationThreadProxy发送了Schedule LaunchActivity 消息,ApplicationThread 是ActivityThread 的一个内部类:
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); 他发了消息出去 所以找实现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
}
}
}
看到了 中间会 handleConfigurationChanged 等配置,(这个操作就对应我们activty的 onConfigurationChanged():方法)然后就是 performLaunchActivity,在看看这个方法里面干了什么事,看它的返回值是个activity ,难道是解析manifest xml信息找到我们的launch的activity呢?继续往下看吧,
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);
上面这个地方获取了activity实例,我们先看看application的实例,因为我们每个应用都是有一个application的,先启动application再是activity才对的,
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
得到了application 实例,
那么 application的oncreate在哪里调到的呢,我们进到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 这个东东发起了 oncreate,那我们进去看下:
/**
* 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();
}
对没错就是它启动了 application的oncreate,这个app就是你自己的额application了,
然后在回到
mInstrumentation.callActivityOnCreate(activity, r.state);
继续看下 callActivityOnCreate实现
/**
* 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);
}
然后就进到了 Activity 里面了:
final void performCreate(Bundle icicle) {
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
之后 activity就调用了自己的onCreate。
哦,原来onCreate 是自己调用的,instrumentation 只是调用了performCreate而已,所以以后要是有人问你,是谁调用了 activty的onCreate,你就大声的告诉他,是activity他自己。
所以是谁启动了activity 那么你可以回到答是instrumentation 这个类,但是完成这个工作是在ActivityThread 这个线程里面来实现的。
不过ActivityThread 也是ApplicationThread 通过handler发消息给它,它才知道执行那个阶段的流程,而ApplicationThread 是 ApplicationThreadProxy 通过binder消息得到的,而 ApplicationThreadProxy 是ActivityMangerService 告诉它的,所以源头应该是ActivityMangerService 来控制。执行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