Service does not work on android 7+

1

I have a background service that lasts approximately 5 minutes and executes X methods every X time each, it is necessary that those times are fulfilled and go consecutive.

The problem is that Android 7 kills the service by "turning off the screen".

Can I do this with a JobScheduler? (the service has timers inside), or should you use a foreground service?

Example of my service:

public class MyServide extends Service {

    class MyBinder extends Binder {
        MyServide getService() {
            return MyServide.this;
        }
    }

    public IBinder onBind(final Intent intent) {
        if (intent != null) {
            Observable.timer(randomTime), TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                   //random code
                });
        }
        return MyBinder;
    }

}
    
asked by Pablo Cegarra 15.03.2018 в 20:40
source

1 answer

1

To keep your service running in the background and not important if you close the application you must overwrite the onStartCommand() method using the START_STICKY property:

  

Service.START_STICKY : Recreate the service if the application is   destroy.

That is to say that if we close the application that started this service, the service continues its operation.

In the case of stopping the service this property does not affect the ability to stop it.

public class MyServide extends Service {

...
...

 @Override
    public int onStartCommand(Intent intent, int flags, int startid) {

        return START_STICKY;
    }

}
answered by 16.03.2018 / 20:06
source