java - Running a Service indefinitely
问题描述
I am migrating my Android App to target Android Oreo. I am running a service which should run indefinitely to perform a particular task.
The running of the service is to perform a particular task with the users' consent of course.
Till now my app has been targeting Android Marshmallow and the service is working fine and is running also fine.
This is my service
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
private void DoSomething() {
//Some Code keep watching something.
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
DoSomething();
return Service.START_STICKY;
}
}
And this is how I am Starting the service from an Activity
startService(new Intent(getBaseContext(), MyService.class));
Now my problem is that when I target my app to Android Oreo then the service is not running and hence the function which I am trying to achieve is not working.
But whereas If my App target Android Marshmallow everything is working fine with the exact same code.
Can anyone help me to run a Serice indefinitely in Android App targeting Android Oreo would be appreciated?
解决方案
在 Android Oreo+ 中,后台服务受到严格限制。要运行您的代码,您有两个选择:使用前台服务或使用 JobScheduler/ WorkManager API 之类的东西。
但它们都不会无限期地工作,并且 WorkManager 仅适用于可延迟的任务。这是我们无能为力的事情。
推荐阅读
- sas - 解释倾向得分导致 SAS 中的分层方法
- php - 如何在phpunit中正确调用laravel的中间件闭包?
- python - SQLAlchemy 中是否有 func.random() 的等价物来查询 teradata 数据库?
- javascript - 尽管设置了 preventdefault,但事件单击触发了两次
- ios - 如何正确安装企业应用程序?
- javascript - Service Worker 错误“未捕获(承诺)DOMException:超出配额。”
- reactjs - 样式表不是 React 组件的样式
- sql - Oracle SQL:获取具有不同列的重复行并对结果有条件
- events - 任何人都可以从默认为行的字段中澄清事件处理程序的执行,或者将我引至源链接
- reactjs - 如何在 React 中使用 AG-Grid?我收到构建错误