Stop A Service After Mainactivity Is Closed (edited)
I think im not clear at all, i do want the service to persist even if the main activity is destroyed via user action or android system does it, it does it well, but when the app is
Solution 1:
If the service already running in background then you need to call stopSelf() on same instance of that service . Now as per service life Cycle onCreate() only call once in the lifetime of service . WhereAs onStartCommand get called each time you call startService() with new intent. So what you can do is to pass a flag in intent to stop it .
Intent BgServiceIntent = newIntent(MainActivity.this, BgScanService.class);
BgServiceIntent.putExtra("close",true);
startService(BgServiceIntent);
And in Service .
@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
boolean shouldClose=intent.getBooleanExtra("close",false);
if(shouldClose){
stopSelf();
} else {
// Continue to action here
}
return START_STICKY;
}
Solution 2:
Maybe all you need to do is check to see if it's null
before attempting to stop it:
private void stopBg(){
if(BgServiceIntent != null)
stopService(BgServiceIntent);
}
Solution 3:
First of all start a service in START_NOT_STICKY. Override this method in your Service
@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
and add this in your MainActivity.class
@override
private onDestroy() {
stopService(YourActiveService);
finishAffinity();
super.onDestroy()
}
Post a Comment for "Stop A Service After Mainactivity Is Closed (edited)"