如果未运行,请检测并运行服务

时间:2017-08-24 13:00:24

标签: android service alarmmanager

如何检测服务是否未运行并在每隔5秒后再次运行服务

 try {


        Intent ishintent = new Intent(this, OnlineWatcherService.class);
        PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pintent);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),5000, pintent);
        Toast.makeText(getApplicationContext(), "service Alaram", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
    }

1 个答案:

答案 0 :(得分:0)

如果检测是否正在运行您的服务,您可以使用以下方法:

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

然后

  if (!isMyServiceRunning(MyService.class)) //do something here