Search code examples
androidandroid-fragmentsbackground-service

Stop BackgroundService when app in background


I have a background service method that called frequently for updated application data. I have a Activity in which multiple fragments are display according to user navigation. I just start service when application is started from my dashboard activity in which i am showing fragments.Now i just want to stop service when user exit from app.I have code for stop service in onDestroy() of my activity,but it never got called when user press android mobile home button and exit from app.

below my code in service -

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    callAsynchronousTask();
    return Service.START_NOT_STICKY;
}

Solution

  • onDestroy() will only called when you close your app or close your activity. when you press home button it does not call. If you still want service to stop when user press home button then you can override onPause() and stop service inside this, but when you open another activity service will stop again.