Application.onCreate 、ContentProvider.onCreate 、 Activity.onCreate 的调用顺序研究
网上看到的一个问题,一开始没想到答案,也是很懵的,于是自己写了个 demo 。在 demo 里打印 log 顺序。先说结果吧
Application.attachBaseContext();
ContentProvider.onCreate();
Application.onCreate();
Activity.onCreate();
一开始,我以为是 Application.onCreate() -> ContentProvider.onCreate() -> Activity.onCreate()
的顺序的。
于是很费解,就找了源码看看。
private void handleBindApplication(AppBindData data) {
// 省略代码
// If the app is being launched for full backup or restore, bring it up in
// a restricted environment with the base application class.
// 1 这里是开始创建 Application , 然后调用 attachBaseContext() 方法
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
// don't bring up providers in restricted mode; they may depend on the
// app's custom Application class
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
// 2 开始初始化 ContentProvider ,
// 个人的理解是防止自定义的 Application 需要使用 ContentProvider 的时候 ContentProvider 没有初始化
installContentProviders(app, data.providers);
// For process that contains content providers, we want to
// ensure that the JIT is enabled "at some point".
mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
}
}
// Do this after providers, since instrumentation tests generally start their
// test thread at this point, and we don't want that racing.
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}
catch (Exception e) {
throw new RuntimeException(
"Exception thrown in onCreate() of "
+ data.instrumentationName + ": " + e.toString(), e);
}
try {
// 3 这里调用 Application 的 onCreate() 方法
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
// 省略代码
}
看代码的确是这样
ContentProvider.onCreate() -> Application.onCreate() -> Activity.onCreate()
为什么是这样,想了想,可能是防止开发者在自定义的 Application 的 onCreate 方法里面使用 ContentProvider 的时候 ContentProvider 没有初始导致错误吧。