java - 后台服务上的 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();
}
解决方案
推荐阅读
- java - Java:Json Response 类转换异常
- python - Selenium Webdriver (Python) - 单击 div 元素(复选框)
- javascript - 为什么 ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana' 的结果是?
- sql - SQL Server:带有内部 SELECT 和子 SELECT 的 SUM()。每次都出错
- javascript - JavaScript - 通过对象数组中存在于预定义列表中的 ID 查找多个对象,而不使用 for 循环
- amazon-web-services - 有什么方法可以验证 IAM 用户
- javascript - 如何在TD标签中添加id?
- svg - ImageMagick:不符合标准的绘图原语定义“px”
- python - 通过终端运行代码时的 Python3 'ModuleNotFoundError',但在 python 虚拟环境中一切正常
- amazon-web-services - 将 athena 表作为一个可读文件导出到 S3