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?
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.