白色保活(多进程保活二)

1 前台服务

1.1 什么是前台服务

前台服务是那些被认为用户知道(用户所认可的)且在系统内存不足的时候不允许系统杀死的服务。前台服务必须给状态栏提供一个通知,它被放到正在运行标题之下——这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除。
###1.2 为什么要使用前台服务
在一般情况下,Service几乎都是在后台运行,一直默默地做着辛苦的工作。但这种情况下,后台运行的Service系统优先级相对较低,当系统内存不足时,在后台运行的Service就有可能被回收。
那么,如果我们希望Service可以一直保持运行状态且不会在内存不足的情况下被回收时,可以选择将需要保持运行的Service设置为前台服务。
###1.3前台服务实践
重写Service的以下方法即可实现一个简单的前台服务。

    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification.Builder builder = new Notification.Builder(this);
        Intent intent1 = new Intent(this,MainActivity.class);
        builder.setContentIntent(PendingIntent.getActivity(this,0,intent1,0))
        .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher))
        .setContentTitle("自定的Title")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentText("自定义的内容")
        .setWhen(System.currentTimeMillis());
        Notification notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND;
        startForeground(123,notification);
        return super.onStartCommand(intent, flags, startId);
    }
    public void onDestroy() {
        stopForeground(123);
        super.onDestroy();
    }

2 粘性服务

粘性服务这个是系统自带的,onStartCommand方法必须具有一个整形的返回值,这个整形的返回值用来告诉系统在服务启动完毕后。Service的onStartCommand方法里返回 STATR_STICK。

3 Service自启动

onDestory中start自启(准确的将算不上进程拉活,只能算service自启,force_stop后不能正常拉活)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值