Stop All Started Services on App Close / Exit
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));
开发者_StackOverflow社区
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!
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)"?
精彩评论