SecurityException: Permission Denial: startForeground requires android.permission.FOREGROUND_SERVICE

Caused by: java.lang.SecurityException: Permission Denial: startForeground from pid=12394, uid=10302 requires android.permission.FOREGROUND_SERVICE

翻译:原因:java.lang.SecurityException:权限拒绝:StartForeground from PID=12394,ULD=10302需要android.permission.foreground

Android在8.0开始限制后台服务,启动后台服务需要设置通知栏,使服务变成前台服务。同时在Android 9.0开始注册权限android.permission.FOREGROUND_SERVICE,并授权权限。

从8.0开始启动服务需要进行判断出来如下:

    /**
     * Android 8.0及以后,启动服务的形式已经变了
     */
    private void startService(Context context) {
        Intent intent = new Intent(context, MyForegroundService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

同时在Service的onCreate()方法里设置通知栏如下:

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("xxx", "xxx", NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager == null)
                return;
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "xxx")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW)
                    .build();
        }
    }

 

你可能感兴趣的:(Android异常解决篇)