你可以尝试创建两个远程服务,在您的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 ... 希望它可以帮助你..