Home » Android » How to restart service in android to call service oncreate again

How to restart service in android to call service oncreate again

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&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));

Answer:

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));
    }
}

Answer:

Why not move the setting stuff from onCreate to a separate method. You can then call this method from onCreate and also call it when you need to change the settings. Then there would be no need to actually restart the service.

Answer:

Use a Method onTaskRemoved(Intent rootIntent) inside service, hence the service restarted again

@Override
public void onTaskRemoved(Intent rootIntent) {
    System.out.println("service in onTaskRemoved");
    long ct = System.currentTimeMillis(); //get current time
    Intent restartService = new Intent(getApplicationContext(),
            PushService.class);
    PendingIntent restartServicePI = PendingIntent.getService(
            getApplicationContext(), 0, restartService,
            0);

    AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    mgr.setRepeating(AlarmManager.RTC_WAKEUP, ct, 1 * 1000, restartServicePI);
}

Answer:

or you can use a delayed handler to start the service. The handler will need to be declared static in a singleton, so its reference is not killed while restarting:

serviceRestartHandler = new Handler ();
serviceRestartHandler.postDelayed (new Runnable () {
            @Override
            public void run() {

                startService (new Intent (mContext, YourWonderfulService.class)
                        .putExtra (flagName, true));
                serviceRestartHandler.removeCallbacksAndMessages (null);
            }
        }, 1000);
        stopSelf ();

Answer:

Just calling again startService() will start the service again if it’s already running, meaning service will be restarted.