startForgroundService

1、启动Service

    public static void startService(Context context) {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {

            context.startForegroundService(new Intent(context, InterceptSercice.class));

        } else {

            context.startService(new Intent(context, InterceptSercice.class));

        }

    }

2、把Service之前台(必须要设置)

    Utils.startForeground(this);

此方法要放在onCreate 或onStartCommand【建议后者】

    public static void startForeground(Service service) {

        if (Build.VERSION.SDK_INT >= 26) {

            if (createNotificationChannelServicesPass(service, Env.CHANNEL_ID_SERVICE)) {

                return;

            }

            Notification notification = new NotificationCompat.Builder(service.getApplicationContext(), Env.CHANNEL_ID_SERVICE)

                    .build();

            // id cannot 0

            service.startForeground(-1, notification);

        }

    }

    private static boolean createNotificationChannelServicesPass(Service service, String channelId) {

        if (Build.VERSION.SDK_INT >= 26) {

            NotificationChannel channel = new NotificationChannel(channelId,

                    service.getResources().getString(R.string.notification_channel_service),

                    NotificationManager.IMPORTANCE_LOW);

            NotificationManager manager = ((NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE));

            if (manager == null) {

                LogUtil.e(TAG, "createNotificationChannel fail");

                return true;

            }

            // channel.setLockscreenVisibility();

            manager.createNotificationChannel(channel);

        }

        return false;

    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容