如何检测服务是否未运行并在每隔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) {
}
答案 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