为什么我得到getApplicationcontext()null?

时间:2015-09-17 05:13:01

标签: android push-notification android-notifications android-intentservice

我不确定它有什么不对!我读到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我得到空值。 任何建议都是最受欢迎的。

4 个答案:

答案 0 :(得分:6)

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

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

中找到

答案 1 :(得分:1)

你应该在你的onCreate方法中调用它,而不是构造函数。在构造函数中,尚未设置应用程序上下文,因此它将为null。

答案 2 :(得分:0)

使用GCMNotificationIntentService.this或仅使用this代替mainContext

IntentService扩展Service,它本身就是Context

的子类

答案 3 :(得分:0)

要以良好的方式获取应用程序上下文,您应该按照以下方式使用。

使用以下方式

第1步

创建一个Application类

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
}
相关问题