Android后台服务中的getContext

8

我正在尝试创建一个即使我的应用程序关闭也可以运行的服务。然而,我需要在这个服务中使用我的应用程序上下文。当应用程序正在运行时,该服务也可以工作,但是当我关闭应用程序(调用onDestroy())时,getContext()始终返回null

服务

public class SubscribeService extends Service {

    private Context context;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this; //Returns null when service is running on background
        context = MyApp.getContext(); //Also null
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //do stuff using context
    }

我的应用程序
public class MyApp extends Application {

    private static Context context;

    public static Context getContext() {
        return context.getApplicationContext();
    }

    @Override
    public void onCreate() {
        context = getApplicationContext();
        super.onCreate();
    }
}

服务从Activity的onCreate()方法启动

startService(new Intent(this, SubscribeService.class));

在这种情况下,我该如何使用Context

编辑

Onik的帮助下,我设法使其正常工作。 我只需要在调用super.onCreate();之前调用MyApp.getContext(); 像这样:

@Override
public void onCreate() {
    context = MyApp.getContext();
    super.onCreate();
}
3个回答

11

Service 类继承自 Context 类。您可以使用 this,其中 this 是对 Service 实例的引用。

在下面关于 SubscribeService 类的代码中,我会提供更多详细信息:

@Override
public void onCreate() {
    super.onCreate();
    context = this;
    context = MyApp.getContext();
}

在您的ServiceonCreate()中,context = this不能为null,这是基本编程范例。


2
在你的帮助下,我设法让它工作了。然而,仅使用 this 是不够的,我必须在 super.onCreate(); 之前使用 context = MyApp.getContext(); - urukh

4
尝试这个: 在MyApp.context = getApplicationContext();之前添加super.onCreate();
public class MyApp extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }
}

编辑:调用 MyApp.getAppContext() 将返回应用程序的 Context


1
是的,就是这样! 谢谢你,我想我需要再多了解一下super调用。 - urukh

1

我曾经留下过一个答案,其中建议在Service中使用getApplicationContext()

此外,在这里使用Context.startService(Intent)可能会更有意义地使用IntentService

... 在调用super.onCreate()之前不要插入语句。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接