为什么我得到 getApplicationcontext() null?

Why am I getting getApplicationcontext() null?

我不确定它有什么问题!我读到 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 的空值。 欢迎提出任何建议。

使用 GCMNotificationIntentService.this 或简单地 this 而不是 mainContext

IntentService 扩展 Service 本身是 Context

的子类

在构造函数中访问应用上下文还为时过早。尝试将此代码移动到 onCreate 方法中。

更多关于生命周期的数据可以在the documentation

中找到

您应该在 onCreate 方法中调用它,而不是在构造函数中。在构造函数中,application context还没有建立,所以它会是null。

为了更好地获取应用程序上下文,您应该使用以下方式。

使用以下方式

步骤 1

创建应用程序class

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>

步骤 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
}