getApplicationContext 返回 null 原因及解决方案
Get application context returns null.
原因
从下面可知 mApplication 在 attachBaseContext 方法被调用之后才被赋值
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
attachBaseContext(context);
.......
mApplication = application;
}
因此,如果在 Application 的 onBaseContextAttached 生命周期方法中使用 Contex ,则不能调用 getApplicationContext 方法。因为,此时 mApplication 还没有被赋值,getApplicationContext 也就是返回 null。
public void onBaseContextAttached(Context base)
解决方案
将你可能需要使用到 Application 或者 Context (可能调用 onBaseContextAttached)的代码,从 onBaseContextAttached 移动到 Application 生命周期方法 onCreate 中。