我正在尝试创建一个即使我的应用程序关闭也可以运行的服务。然而,我需要在这个服务中使用我的应用程序上下文。当应用程序正在运行时,该服务也可以工作,但是当我关闭应用程序(调用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();
}
this
是不够的,我必须在super.onCreate();
之前使用context = MyApp.getContext();
。 - urukh