Android app保活(前台服务)

国内厂商定制,除非厂商给app白名单,否则只能用户手动添加白名单(应用自启和后台运行),才能通过前台服务实现app保活。

这里介绍前台服务相关实现方式。

开启服务:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //安卓8.0以上开启为前台服务
            startForegroundService(new Intent(this, KeepAliveNotificationService.class));
        } else {
            startService(new Intent(this, KeepAliveNotificationService.class));
        }

服务:

public class KeepAliveNotificationService extends Service {
    private final String CHANNEL_ONE_ID = "100";

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


    @Override
    public void onCreate() {
        super.onCreate();
        //创建通知栏常驻通知
        initNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //        return super.onStartCommand(intent, flags, startId);
        //返回START_STICKY,被系统或手动清理后可重启
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
    }

    /**
     * 开启通知栏
     */
    private void initNotification() {
        //获取管理器
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //创建点击跳转Activity
        Intent intent = new Intent(this, NotificationActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        //创建notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ONE_ID)
                .setContentIntent(pendingIntent) // 设置PendingIntent
                .setSmallIcon(R.mipmap.user_notification_ic_launcher) // 设置状态栏内的小图标
                //.setLargeIcon(bitmapIcon)// 设置大图标
                .setContentTitle("推送服务")
                .setContentText("应用更好的接收推送服务") // 设置内容
                .setWhen(System.currentTimeMillis())// 设置该通知发生的时间
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)// 锁屏显示全部通知
                //.setDefaults(Notification.DEFAULT_ALL)// //使用默认的声音、振动、闪光
                .setCategory(Notification.CATEGORY_SERVICE)//设置类别
                .setPriority(NotificationCompat.PRIORITY_MAX);// 优先级为:重要通知


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //安卓8.0以上系统要求通知设置Channel,否则会报错
            NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, "服务常驻通知", NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);//锁屏显示全部通知
            manager.createNotificationChannel(notificationChannel);
            builder.setChannelId(CHANNEL_ONE_ID);
        }
        Notification notification = builder.build(); // 获取构建好的Notification
        //notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        notification.flags = Notification.FLAG_NO_CLEAR;//不消失的常驻通知
        startForeground(1, notification);//设置常驻通知

    }
}

清单文件

  
        

你可能感兴趣的:(android)