I'm trying to keep service running continously until user close app.
I'm using startService()
method from onCreate()
method of my main activity and stopService()
in onDestroy()
method.
Now I have problem, because it seems that my main activity dies and is re-created when I rotate device or when I turn off screen.
How can I stop my service only when user stops app manually?
First, the easiest way to do what you're trying to do is to launch an Android Broadcast when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart after that. Dear Dr Sabri Allani, If your Service is started by your app then actually your service is running on main process.
Therefore, the best way to stop the service is by calling stopService() in the onStop() method as shown below. You'll just need the context of the Activity to start service from a separate thread. Rest all implementation of Service will be the same.
Stop Services Running in BackgroundOpen Settings of the phone. Now, go to the Developer Options. Tap on Running Services. Tap on the app for which you want to limit battery usage, now tap on stop.
To remove the service from the foreground, call stopForeground() . This method takes a boolean, which indicates whether to remove the status bar notification as well. Note that the service continues to run. If you stop the service while it's running in the foreground, its notification is removed.
Set the below attribute in your service tag in the manifest file,
<service android:name="service" android:stopWithTask="true"/>
adding this will call the ondestroy()
of the service when the task is removed (app closed from recent apps list).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With