35

我的 Android 应用程序中有一个始终运行的服务。现在我通过 GCM 从我的服务器获得了一个设置,并将这些设置更新到我的服务中。我将我的设置放在服务的 oncreate 中。所以我需要重新启动我的服务以获取最新设置。如何重新启动我的服务?

4

7 回答 7

49

紧接着调用这两个方法,这将导致Service停止和启动。不知道任何“重新启动”它的方法。这就是我在我的应用程序中实现它的方式。

stopService(new Intent(this, YourService.class));
startService(new Intent(this, YourService.class));
于 2012-11-05T08:13:26.473 回答
15

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

当需要重启服务时只需调用

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

public void onDestroy()
{
   if (RESTARTSERVICE)
    {
       startService(new Intent(this, CLASS_OF_SERVICE.class));
    }
}
于 2015-03-12T13:47:14.937 回答
4

为什么不将设置内容从 onCreate 移至单独的方法。然后,您可以从 onCreate 调用此方法,并在需要更改设置时调用它。然后就不需要实际重新启动服务了。

于 2012-11-05T07:26:04.847 回答
2

在服务内部使用方法 onTaskRemoved(Intent rootIntent),因此服务再次重新启动

@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);
}
于 2016-09-07T05:51:06.637 回答
0

在 KOTLIN 中,您可以这样做:

        AppLog.i("System UI Service is Restarting")
        val startSystemUiIntent = Intent(context, AwesomeService::class.java)
        val restartServicePendingIntent = PendingIntent.getService(context, 1, startSystemUiIntent, PendingIntent.FLAG_ONE_SHOT)

        val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, SystemClock.currentThreadTimeMillis(), restartServicePendingIntent)


        stopService(Intent(context, SystemUIService::class.java))
于 2021-02-04T13:42:29.043 回答
-1

或者您可以使用延迟处理程序来启动服务。处理程序需要在单例中声明为静态,因此在重新启动时不会终止其引用:

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 ();
于 2020-01-29T12:14:32.527 回答
-7

startService()如果服务已经运行,再次调用将再次启动服务,这意味着服务将重新启动。

于 2014-09-30T06:26:37.283 回答