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?
Answer
In Android Oreo+, background services have been severely restricted. To run your code, you've two options: use a Foreground service or use something like JobScheduler/WorkManager APIs.
Neither of them will work indefinitely though and WorkManager is only meant for deferrable tasks. This is something that we can't do much about.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM