一、Application是什么
看看源码中官方注释解释
/**
* Base class for maintaining global application state. You can provide your own
* implementation by creating a subclass and specifying the fully-qualified name
* of this subclass as the "android:name"
attribute in your
* AndroidManifest.xml’s <application>
tag. The Application
* class, or your subclass of the Application class, is instantiated before any
* other class when the process for your application/package is created.
*
* There is normally no need to subclass
* Application. In most situations, static singletons can provide the same
* functionality in a more modular way. If your singleton needs a global
* context (for example to register broadcast receivers), include
* {@link android.content.Context#getApplicationContext() Context.getApplicationContext()}
* as a {@link android.content.Context} argument when invoking your singleton’s
*/
大概意思是:
Application类是用来维护应用程序全局状态。你可以提供自己的实现,并在 AndroidManifest.xml文件的application标签中指出他的名字。
android:name=
当你的应用程序进程被创建后Application类将是第一个被实例化的相比于
activity,service,broadcast,content provider这些组件。
Android系统会为每个程序运行时创建一个Application类的对象且仅创建一个,所以Application可以说是单例 (Singleton)模式的一个类。且 Application 对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。因为它是全局唯一的,所以在不同的Activity,Service中获得的对象都是同一个对象。
二、 Application 的创建过程
在ActivityThread中,名为H的Handler的handlerMessage方法中处理了关于一个android应用程序重要组件的生命周期等方法,Application也是在此被创建与销毁且优先于其他组件执行。
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
"bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case EXIT_APPLICATION:
if (mInitialApplication != null) {
mInitialApplication.onTerminate();
}
Looper.myLooper().quit();
break;
handleBindApplication(data)里面调用LoadedApk.makeApplication方法创建application对象,紧接着调用application的onCreate生命方法:
try {
//...
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
//..
}
}
//..
if (instrumentation != null) {
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
//..
}
}
在loadedApk里接着调用Instrumentation.makeApplication方法:
static public Application newApplication(Class<?> clazz, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = (Application)clazz.newInstance();
app.attach(context);
return app;
}
在方法中使用了类加载器加载生成application类对象。接着调用application的attach方法初始化。
三、BootstrapApplication
如果发现此时加载的application是
com.android.tools.fd.runtime.BootstrapApplication
是因为androidstudio2.0版本中新添加的Instant run即时编译技术修改了AndroidManifest文件,解释如下:
热更新机制:修改代码不需要重启&#x