Android 后台服务上的 getContext

Android getContext on a background Service

我正在尝试创建一个 服务,它即使在我的应用程序关闭时也能运行。但是,我需要在此 Service 中使用我的应用程序 Context。当应用程序为 运行 时,服务也可以正常工作,但是当我关闭应用程序(调用 onDestroy() )时,getContext() 总是 returns 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
    }

MyApp

public class MyApp extends Application {

    private static Context context;

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

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

服务从ActivityonCreate()

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

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

编辑

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

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

Service extends Context。您可以使用 this,其中 this 是对 Service 实例的引用。

在下面关于 SubscribeService class:

代码的评论中提供更多详细信息
@Override
public void onCreate() {
    super.onCreate();
    context = this;
    context = MyApp.getContext();
}

在您的 Service 中,onCreate() context = this 无法通过基本编程范式 null

已经留下了一个answer,要在Service中使用getApplicationContext()

此外,使用 IntentServiceContext.startService(Intent) 在这里可能有意义。

...并且在调用 super.onCreate().

之前不要插入语句

试试这个:

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() 将 return 应用程序 Context