Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart service in android to call service oncreate again

I have a service in my Android Application which runs always.Now i have a settings from my server through GCM and update these settings to my service. I put my settings in oncreate of service. So i need to restart my service to fetch latest settings. How to restart my service?

like image 587
Ramprasad Avatar asked Nov 05 '12 07:11

Ramprasad


People also ask

Can we start the same service twice?

If you call startService() multiple times, the service will be called with onStartCommand() multiple times, one per call to startService() . Whether it will "restart" will depend upon whether the service was still considered to be running from the previous startService() call.

Can we start a service multiple times in Android?

Absolutely Correct. Only one instance of Service is created for an application process. And when you call StartService(); again, then only onStartCommand() gets called and new Intent is passed to onStartCommand() method. Note: onCreate() is not called again.

How do I start a service from activity?

A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. A service is bound when an application component binds to it by calling bindService().

What happens when a service starts in Android?

Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at the same time.


2 Answers

Call this two methods right after each other, which will causes the Service to stop and start. Don't know any method that "restarts" it. This is how I have implemented it in my application.

stopService(new Intent(this, YourService.class)); startService(new Intent(this, YourService.class)); 
like image 97
Carnal Avatar answered Sep 20 '22 13:09

Carnal


The best solution is to use onDestroy().

When need to restart the service just call

RESTARTSERVICE = true; stopService(new Intent(this, CLASS_OF_SERVICE.class)); 

and

public void onDestroy() {    if (RESTARTSERVICE)     {        startService(new Intent(this, CLASS_OF_SERVICE.class));     } } 
like image 33
Saif Avatar answered Sep 20 '22 13:09

Saif