How to restart service in android to call service oncreate again

ぃ、小莉子 提交于 2019-11-28 08:03:45

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

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

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.

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

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

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