你可以嘗試創建兩個遠程服務,在您的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 ... 希望它可以幫助你..