配置前台服务报错:Permission Denial: startForeground & Bad notification for startForeground

在配置前台服务时,笔者遇到了两个报错,首先遇到的错误如下:

Permission Denial: startForeground

这是由于配置前台服务时,首先需要给予权限,在AndroidManifest中插入如下语句:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

此时便分配了前台服务的权限,但直接运行有可能会出现第二个错误:

Bad notification for startForeground

这是因为Android 8.0之后的版本对通知做了细分,引进了channel,而这会影响普通通知与前台服务通知,而我们遇到的就是后者的问题。此时需要在代码中配置NotificationChannel,并在通知中设置channel的值。具体代码如下:

String CHANNEL_ONE_ID = "example";
String CHANNEL_ONE_NAME = "Channel One";
NotificationChannel notificationChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
    notificationChannel.enableLights(true);
    notificationChannel.setLightColor(Color.RED);
    notificationChannel.setShowBadge(true);
    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.createNotificationChannel(notificationChannel);
}

Notification notification=new NotificationCompat.Builder(this).setChannelId(CHANNEL_ONE_ID);

最后一行示例了设置通知channel的操作。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值