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

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后不能正常拉活)

猜你喜欢

转载自blog.csdn.net/weixin_40876113/article/details/80894131