首页 > 解决方案 > 后台服务上的 Android getContext

问题描述

我正在尝试创建一个即使在我的应用程序关闭时也能运行的服务。但是,我需要在此Service中使用我的应用程序上下文。当应用程序运行时,该服务也可以正常工作,但是当我关闭应用程序(调用 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));

在这种情况下我应该如何使用上下文?

编辑

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

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

标签: javaandroidandroid-serviceandroid-context

解决方案


服务扩展上下文。您可以使用, 对实例的引用在this哪里。thisService

在下面关于SubscribeService类的以下代码的评论中提供更多详细信息:

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

在您Service的 'sonCreate() context = this中,不能通过null基本的编程范式。


推荐阅读