How to get know when app removed from background?

746 Views Asked by At

I have some tasks which is running in service. I need it to be running even if the app goes in to background. Its working fine. The problem is, How do I know When my app is removed from background?? In this scenario, I cannot stop my service and which leads to crash. Anybody please help, Thanks in advance.

2

There are 2 best solutions below

1
On

I think this way you can prevent to stop background service,
In your Service class you need to return START_STICKY in onStartCommand;

Like this,

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    return START_STICKY;
}

If someone try to force stop service from background process, then android automatically restart your service with START_STICKY.

I hope this will help you.

2
On

I think implementing the onDestroy() method in your main class from where you are binding the Service can help