Android雙程序守護service保活
阿新 • • 發佈:2019-01-07
package com.guardservice; import com.guardservice.aidl.GuardAidl; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; public class LocalService extends Service { private MyBilder mBilder; @Override public IBinder onBind(Intent intent) { if (mBilder == null) mBilder = new MyBilder(); return mBilder; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { this.bindService(new Intent(LocalService.this, RemoteService.class), connection, Context.BIND_ABOVE_CLIENT); Notification notification = new Notification(R.drawable.ic_launcher, "安全服務啟動中", System.currentTimeMillis()); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); notification.setLatestEventInfo(this, "安全服務", "安全服務...", pendingIntent); startForeground(startId, notification); return START_STICKY; } private class MyBilder extends GuardAidl.Stub { @Override public void doSomething() throws RemoteException { Log.i("TAG", "繫結成功!"); Intent localService = new Intent(LocalService.this, RemoteService.class); LocalService.this.startService(localService); LocalService.this .bindService(new Intent(LocalService.this, RemoteService.class), connection, Context.BIND_ABOVE_CLIENT); } } private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.i("TAG", "RemoteService被殺死了"); Intent localService = new Intent(LocalService.this, RemoteService.class); LocalService.this.startService(localService); LocalService.this .bindService(new Intent(LocalService.this, RemoteService.class), connection, Context.BIND_ABOVE_CLIENT); } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("TAG", "RemoteService連結成功!"); try { if (mBilder != null) mBilder.doSomething(); } catch (RemoteException e) { e.printStackTrace(); } } }; }