Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/204.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 为什么获取getApplicationcontext()null?_Android_Push Notification_Android Notifications_Android Intentservice - Fatal编程技术网

Android 为什么获取getApplicationcontext()null?

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;

我不知道有什么不对!我读到Intentservice本身是
上下文的一个子类

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
}