2017-08-24 69 views
0

如何检测,如果服务没有运行,和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

对于检测正在运行的服务或不是你可以用下面的方法:

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