Android 为什么获取getApplicationcontext()null?
我不知道有什么不对!我读到Intentservice本身是Android 为什么获取getApplicationcontext()null?,android,push-notification,android-notifications,android-intentservice,Android,Push Notification,Android Notifications,Android Intentservice,我不知道有什么不对!我读到Intentservice本身是上下文的一个子类 public class GCMNotificationIntentService extends IntentService { private NotificationManager mNotificationManager; NotificationCompat.Builder builder; Context mainContext; WriteFile writeFile;
上下文的一个子类
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
的空值。
欢迎提出任何建议。使用gcmnotificationtentservice。此
或干脆this
而不是mainContext
IntentService
扩展了服务
,它本身是上下文
的一个子类。在构造函数中,访问应用程序上下文为时尚早。尝试将此代码移动到onCreate
方法中
有关生命周期的更多数据可以在中找到,您应该在onCreate方法中调用它,而不是在构造函数中。在构造函数中,应用程序上下文尚未设置,因此它将为null。要以良好的方式获取应用程序上下文,应按以下方式使用
用下面的方法
步骤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清单文件中声明以下内容
<application android:name="com.xyz.MyApplication">
...
</application>
像
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
}