【无标题】

Android 遇到:android.app.RemoteServiceException$CannotPostForegroundServiceNotificationException: Bad notification for startForeground : 如何解决:
原因:API版本大于18,直接使用 new Notification() 来创建前台服务的通知仍然是不被接受的,因为这没有提供必要的通知细节(如图标、标题),违反了Android对于前台服务通知的规定。从Android 8.0(API 26)开始,还需要通过通知渠道发送通知。
针对您的代码,应该进行如下修改:
创建通知渠道(针对API 26及以上)。
构建一个完整的通知,包含必要的元素(小图标、标题、内容)。
解决方案:在对应使用Notification 的服务中修改
@Override
public void onCreate() {
Log.i(TAG, “CoreInnerService -> onCreate”);
super.onCreate();

        // 创建通知渠道,针对Android 8.0及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "VM Daemon Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "CoreInnerService -> onStartCommand");
      //  startForeground(CORE_SERVICE_ID, new Notification());
        //确保服务运行在前台
        Notification notification = new Notification.Builder(this, CHANNEL_ID)
                .setContentTitle("交通安全管控正在运行")
                .setContentText("正在运行")
                .setSmallIcon(R.drawable.ic_launcher) // 设置图标,需替换为实际资源ID
                .build();
        startForeground(CORE_SERVICE_ID, notification);
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值