2016-09-28 93 views
0

我在尝试有两个服务互相监视。如果没有运行,我想在备份服务上重新创建它。互相监控的服务

我知道我可以使用AlarmManager每隔x秒监视一次,但如果服务正在运行,我该如何监视它们?

我在做这样的事情,但我的服务是没有显示出来:

ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE); 
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) 
{ 
    if(ServiceObserverOne.class.getName().equals(service.service.getClassName())) 
    { 
     return true; 
    } 
} 

回答

0

你可以尝试创建两个远程服务,在您的manifest.xml宣布他们

<service 
    android:name="ServiceOne" 
    android:process=":remote" > 
    <intent-filter> 
     <action android:name="***.ServiceOne" /> 
    </intent-filter> 
</service> 

<service 
    android:name="ServiceTwo" 
    android:process=":remote" > 
    <intent-filter> 
     <action android:name="***.ServiceTwo" /> 
    </intent-filter> 
</service> 

然后在MainActivity中创建一个可检查服务状态的静态方法(如果服务返回false,则应重新启动该服务):

public static boolean isServiceWorked(Context context, String serviceName) { 
    ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
    ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(Integer.MAX_VALUE); 
    for (int i = 0; i < runningService.size(); i++) { 
     if (runningService.get(i).service.getClassName().toString().equals(serviceName)) { 
      return true; 
     } 
    } 
    return false; 
} 

最后一步是尝试监视serviceOne时ServiceTwo开始工作:

public class ServiceTwo extends Service { 

public final static String TAG = "com.example.ServiceTwo"; 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.e(TAG, "onStartCommand"); 

    thread.start(); 
    return START_REDELIVER_INTENT; 
} 

Thread thread = new Thread(new Runnable() { 

    @Override 
    public void run() { 
     Timer timer = new Timer(); 
     TimerTask task = new TimerTask() { 

      @Override 
      public void run() { 
       Log.e(TAG, "ServiceTwo Run: " + System.currentTimeMillis()); 
       boolean b = MainActivity.isServiceWorked(ServiceTwo.this, "***.ServiceOne"); 
       if(!b) { 
        Intent service = new Intent(ServiceTwo.this, ServiceOne.class); 
        startService(service); 
       } 
      } 
     }; 
     timer.schedule(task, 0, 1000); 
    } 
}); 
} 

ServiceOne相同ServiceTwo ... 希望它可以帮助你..