App保活

查看App是否保活成功:https://my.oschina.net/huiyun/blog/1476143

主要思路: 主要是两个service的相互绑定,以及对链接状态的监听,一旦断开就重新启动和绑定。

  1. 通过Activity发送一个广播(OneReceiver),通过广播OneReceiver启动一个Service(MyService)
  2. 在MyService的onCreate()方法中初始化链接监听类【在Service里写一个类继承接口ServiceConnection,并在方法onServiceDisconnected()中启动OtherService并且与之绑定】
    
  3.  在MyService的onStartCommand()方法绑定OtherService,并写一个Notification,用startForeground()方法启动在通知栏,即提高该Service的优先级。
    
  4.  再创建一个OtherService(就是之前提到的),逻辑与MyService相同,唯一的不同就是在AndroidManifest.xml文件中注册时应将该服务现在另外的进程中,防止该App被kill时连带着OtherService也被kill,这样就无法实现相互唤醒了。
    

下面是主要的代码: MainActivity的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendBroadcast(new Intent(this,MyReceiver.class));
    }
}

MyReceiver的代码:

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context,MyService.class);
        context.startService(intent1);
    }
}

MyService的代码:

public class MyService extends Service {
    private MyServiceConnection connection;
    private MyBinder binder;
    private PendingIntent pendingIntent;

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connection = new MyServiceConnection();
        if (binder == null) {
            binder = new MyBinder();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startService(new Intent(MyService.this, OtherService.class));
        bindService(new Intent(MyService.this, OtherService.class), connection, Context.BIND_IMPORTANT);
        //根据具体的项目需求改判断,这里假设是判断App是否
        if (isAppRunning()) {
            Intent main = new Intent(MyService.this,MainActivity.class);
            startActivity(main);
        }
        intent = new Intent(MyService.this, OtherReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(MyService.this)
                .setContentTitle("MyService提示:")
                .setContentText("MyService 的内容。。。。")
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .build();
        startForeground(startId, notification);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    class MyBinder extends Binder {
    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("SaveApp", "MyServiceConnection : Connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("SaveApp", "MyServiceConnection : Disconnected");
            MyService.this.startService(new Intent(MyService.this,OtherService.class));
            MyService.this.bindService(new Intent(MyService.this,OtherService.class),connection,Context.BIND_IMPORTANT);
        }
    }

    public boolean isAppRunning() {
        ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals("demo.jhc.cn.jpush") && info.baseActivity.getPackageName().equals("demo.jhc.cn.jpush")) {
                return true;
            }
        }
        return false;
    }
}

OtherService的代码:

public class OtherService extends Service {
    private OtherBinder binder;
    private OtherServiceConnection connection;
    private PendingIntent pendingIntent;

    public OtherService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connection = new OtherServiceConnection();
        if (binder == null) {
            binder = new OtherBinder();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bindService(new Intent(OtherService.this, MyService.class), connection, Context.BIND_IMPORTANT);
        if (isAppRunning()) {
            intent = new Intent(OtherService.this, MainActivity.class);
        }
        pendingIntent = PendingIntent.getBroadcast(OtherService.this, 0, intent, 0);
        Notification notification = new NotificationCompat
                .Builder(this)
                .setContentTitle("OtherService title")
                .setContentText("OtherService content")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        notification.flags |=  Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    class OtherBinder extends Binder {
    }

    class OtherServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("SaveApp", "MyServiceConnection : Connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("SaveApp", "MyServiceConnection : Disconnected");
            OtherService.this.startService(new Intent(OtherService.this,MyService.class));
            OtherService.this.bindService(new Intent(OtherService.this,MyService.class),connection,Context.BIND_IMPORTANT);
        }
    }

OtherReceiver的代码:

public class OtherReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Other Receiver : 模拟Jpush接收器",Toast.LENGTH_SHORT).show();
    }
}

转载于:https://my.oschina.net/huiyun/blog/1476079

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值