2016-09-28 75 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 ... 希望它可以幫助你..