如何在android中重启服务再次调用服务oncreate

Ram*_*sad 31 android android-service

我的Android应用程序中有一项服务,它总是运行.现在我通过GCM从我的服务器获得设置并将这些设置更新到我的服务.我把我的设置放在了oncreate of service上.所以我需要重新启动我的服务以获取最新设置.如何重启我的服务?

Car*_*nal 44

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));
Run Code Online (Sandbox Code Playgroud)

  • 由于意图是异步的,此解决方案是否没有竞争条件? (2认同)

小智 15

最好的解决方案是使用onDestroy().

当需要重新启动服务时才调用

RESTARTSERVICE = true;
stopService(new Intent(this, CLASS_OF_SERVICE.class));
Run Code Online (Sandbox Code Playgroud)

public void onDestroy()
{
   if (RESTARTSERVICE)
    {
       startService(new Intent(this, CLASS_OF_SERVICE.class));
    }
}
Run Code Online (Sandbox Code Playgroud)