【问题标题】:Why am I getting getApplicationcontext() null?为什么我得到 getApplicationcontext() null?
【发布时间】:2015-12-13 21:21:38
【问题描述】:
我不确定它有什么问题!我读到here,Intentservice 本身就是Context 的子类。
public class GCMNotificationIntentService extends IntentService {
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context mainContext;
WriteFile writeFile;
public GCMNotificationIntentService() {
super("GcmIntentService");
mainContext = getApplicationContext();
writeFile = new WriteFile(mainContext);
}
// My rest of the code
}
但我得到了 mainContext 的空值。
欢迎提出任何建议。
【问题讨论】:
标签:
android
push-notification
android-notifications
android-intentservice
【解决方案2】:
您应该在 onCreate 方法中调用 this,而不是在构造函数中。在构造函数中,还没有设置应用上下文,所以会为null。
【解决方案3】:
为了更好地获取应用上下文,你应该按照以下方式使用。
使用以下方式
第 1 步
创建一个应用程序类
public class MyApplication extends Application{
private static Context context;
public void onCreate(){
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
第 2 步
在 Android Manifest 文件中声明如下
<application android:name="com.xyz.MyApplication">
...
</application>
第 3 步
使用以下方法在应用程序的任何位置调用应用程序上下文。
MyApplication.getAppContext();
喜欢,
public class GCMNotificationIntentService extends IntentService {
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context mainContext;
WriteFile writeFile;
public GCMNotificationIntentService() {
super("GcmIntentService");
mainContext = MyApplication.getAppContext();
writeFile = new WriteFile(mainContext);
}
// My rest of the code
}
【解决方案4】:
使用GCMNotificationIntentService.this 或简单地使用this 而不是mainContext。
IntentService 扩展了Service,它本身就是Context 的子类