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

Broadcast Receiver调用正常但通知不显示问题求助

问题排查:BroadcastReceiver中通知无法显示的解决办法

核心错误

你的代码只完成了Notification对象的构建,但没有调用NotificationManager发送通知——NotificationCompat.Builder.build()仅生成通知实例,不会自动触发显示,必须主动调用notify()方法。

修改后的完整代码

class ForegroundLocationServicesRestarter : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        if (intent?.action != ForegroundLocationService.ACTION_RESTART_LOCATION_UPDATES) {
            return
        }

        val notificationChannelId = "restartDeliveryApp"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
            val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(notificationChannel)
        }

        val fullScreenIntent = Intent(context, DeliveryManActivity::class.java)
        fullScreenIntent.putExtra("RESTART_TRIGGERED", true)

        // Android 12+建议添加FLAG_IMMUTABLE/FLAG_MUTABLE,避免兼容性问题
        val fullScreenPendingIntent = PendingIntent.getActivity(
            context, 0,
            fullScreenIntent, 
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notification = NotificationCompat.Builder(context, notificationChannelId)
            .setSmallIcon(R.drawable.ic_truck_red)
            .setContentTitle(context.getString(R.string.restarter_title))
            .setContentText(context.getString(R.string.restarter_message))
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_CALL)
            .setFullScreenIntent(fullScreenPendingIntent, true)
            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
            .build()

        // 关键:获取通知管理器并发送通知,使用唯一的通知ID避免冲突
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(1001, notification)
    }
}

额外检查点

  • 确认R.drawable.ic_truck_red资源存在:小图标是通知显示的必要条件,资源缺失会导致通知静默失败
  • Android 13+需确保已申请POST_NOTIFICATIONS权限(你提到已获取,可忽略这条)

关于已有服务通知的疑问

已有前台服务的通知不会影响此通知的显示:

  • 若两者使用不同的通知ID,系统会分别展示
  • 若通知ID重复,新通知会覆盖旧的服务通知
    你当前使用了独立的通知通道,只要保证通知ID唯一,就不会有冲突问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:41:35