0

我需要在后台运行服务,而它一直被 Android 杀死,我需要一次又一次地启动它。由于某些编程目的,我需要知道服务是否正在运行。那是因为我将同时启动第二个服务,并且它会保持两次启动方法。

到目前为止,我已经尝试过:

private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager
            .getRunningServices(Integer.MAX_VALUE)) {
        if (NotificationService.class.getName().equals(
                service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

但是正如我所读到的那样,只有在我的服务启动时才有可能

startService(Intent);

而且因为我每 2 分钟使用 AlarmManager 启动我的服务,所以我不知道如何检查服务是否正在运行。也许如果您知道如何避免两次或多次使用服务启动方法,我会很满意。

4

1 回答 1

0

In services onCreate() method is called when the service is created for the first time. you can do all declarations in it.

onStartCommand() 

is called again and again when you try to call it though alarm manager.

If you want that you service does not get killed then you can run the service on a different process.For this you would need Inter Process Communication(IPC).

For doing this you declare the service in the manifest file as follows:

<service
    android:name="myservice"
    android:process=":my_process">
<service>

the colon(:)my_process in the android:process line tell android system that the name of the process is my_process and the :tells that it is private to the application declaring it.

Reference:complete tutorial on services

于 2012-12-10T14:43:35.163 回答