Is it possible to stop all started services when the user hits the Home Button?
I use:
startService(new Intent(ClassName.this, ClassName2.class));
stopService(new Intent(ClassName.this, ClassName2.class));
This means I will have to somehow add the 'stopService()' for 7+ of my app classes I've researched this topic and I think there's 'onTerminate' but still not sure how this should be implemented.
Any help or hints would be appreciated! Thanks!
Fundamentals of Android Services it can be stopped explicitly using stopService() or stopSelf() methods. with the service effectively by returning an IBinder object. If the binding of service is not required then the method must return null.
A started service is one that another component starts by calling startService() , which results in a call to the service's onStartCommand() method.
In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.
They are system (services such as window manager and notification manager) and media (services involved in playing and recording media). These are the services that provide application interfaces as part of the Android framework.
Is it possible to stop all started services when the user hits the Home Button?
Not directly. For starters, you have no way of knowing they pressed HOME.
If you only want the service running while activities are using it, consider getting rid of startService()
. Instead, use bindService()
in the onStart()
methods of the activities that need the service, and call unbindService()
in their corresponding onStop()
methods. You can use BIND_AUTO_CREATE
to have the service be lazy-started when needed, and Android will automatically stop the service after all connections have been unbound.
If you want services to stop when the user leaves your app, I would ask if you want to use services at all. You may just be making your application way more complicated than it needs to be.
Also, this line is really questionable:
startService(new Intent(ClassName.this, ClassName2.class));
You are making an Intent whose action is the class name of one class, and data URI is the class name of another class...! Maybe you mean something like "new Intent(context, MyService.class)"?
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