Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop All Started Services on App Close / Exit

Tags:

android

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!

like image 916
Rad The Mad Avatar asked Apr 18 '10 00:04

Rad The Mad


People also ask

How do I stop Android service by itself?

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.

What is started service in Android?

A started service is one that another component starts by calling startService() , which results in a call to the service's onStartCommand() method.

How do you stop an app from closing?

In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.

What are system services in Android?

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.


2 Answers

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.

like image 88
CommonsWare Avatar answered Sep 21 '22 14:09

CommonsWare


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)"?

like image 22
hackbod Avatar answered Sep 19 '22 14:09

hackbod