How to restart service in android to call service oncreate again

蹲街弑〆低调 提交于 2019-11-27 02:08:53

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/13227697/how-to-restart-service-in-android-to-call-service-oncreate-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!