如何确保你没有启动两次android服务

时间:2012-03-08 23:13:06

标签: android service

有没有办法在启动服务之前检查服务是否已经运行?

如果它可以在服务的onCreate()中,它会更好,

谢谢!

3 个答案:

答案 0 :(得分:34)

您无法启动服务两次,如果您尝试再次启动它,它将继续运行。 Link to the Android docs.

答案 1 :(得分:0)

我刚刚在 Android 9 (API 28) 上测试过,您可以根据需要多次使用相同的 Intent 启动相同的服务:

onCreate() {
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
    startMyService();
}
private void startMyService() {
    Intent serviceIntent = new Intent(this, MyService.class);
    ContextCompat.startForegroundService(this, serviceIntent);
}

避免这种情况的一种方法是在启动它之前通过传递相同的 Intent 来停止它:

private void startMyService() {
    Intent serviceIntent = new Intent(this, MyService.class);
    stopService(serviceIntent); // <<<<< this line makes sure that you don't start it twice or more times
    ContextCompat.startForegroundService(this, serviceIntent);
}

答案 2 :(得分:-1)

使用服务中的布尔/标志来修复它。  (服务只能启动一次)