You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android SDK28下调用startForeground启动BLE广告崩溃问题求助

问题解决:前台服务通知导致的崩溃

你的崩溃核心原因是Android 8.0(API 26)及以上版本要求前台服务的通知必须绑定有效通知渠道,权限问题已解决(所以不再触发SecurityException),但通知本身不符合系统规范,直接引发崩溃。

修复代码

1. 初始化通知渠道

在Service的onCreate()方法中创建通知渠道(只需执行一次):

private static final String BLE_AD_CHANNEL_ID = "ble_advertise_channel";
private static final String BLE_AD_CHANNEL_NAME = "蓝牙广告状态";

@Override
public void onCreate() {
    super.onCreate();
    // 仅针对Android 8.0+创建渠道
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                BLE_AD_CHANNEL_ID,
                BLE_AD_CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW // 前台服务通知用低优先级即可
        );
        channel.setDescription("显示蓝牙广告的运行状态");
        
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

2. 修改通知构建逻辑,关联渠道

更新goForeground()方法中的通知创建代码,指定已创建的渠道ID:

private void goForeground() {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    // 适配API 23+的PendingIntent flag,避免兼容性警告
    int pendingIntentFlags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M 
            ? PendingIntent.FLAG_IMMUTABLE 
            : 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, pendingIntentFlags);

    Notification.Builder builder = new Notification.Builder(this);
    // Android 8.0+必须设置渠道ID
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId(BLE_AD_CHANNEL_ID);
    }

    Notification n = builder
            .setContentTitle("Advertising device via Bluetooth")
            .setContentText("This device is discoverable to others nearby.")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();

    try {
        startForeground(FOREGROUND_NOTIFICATION_ID, n);
    } catch (SecurityException e) {
        Toast toast = Toast.makeText(this, e.getMessage() + " Exception Throwed", Toast.LENGTH_SHORT);
        toast.getView().setBackgroundColor(Color.parseColor("#FF0FF0"));
        toast.show();
    }
}

额外检查点

  • 确认R.drawable.ic_launcher是有效图标:不能全透明,必须包含可见的不透明像素,否则系统会判定通知无效。
  • FOREGROUND_NOTIFICATION_ID需设为唯一正整数(比如1001)。

内容的提问来源于stack exchange,提问作者BuePhil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:26:01