在FCM中实现设备震动与LED闪烁功能遇阻求助
解决FCM通知震动与LED闪烁失效问题
你的问题核心在于Android 8.0(API 26)及以上版本中,通知的震动、LED灯光等行为完全由通知通道(NotificationChannel)控制,你当前的代码仅在NotificationCompat.Builder中设置了震动和灯光,但没有在通道上配置对应属性,导致这些设置被系统忽略。此外,你设置的LED颜色为0(黑色),这也会导致灯光无法正常显示。
修复步骤:
- 配置通知通道的震动与灯光属性:创建
NotificationChannel时,必须显式开启震动、设置震动模式,同时配置LED灯光颜色并开启灯光功能。 - 修正LED灯光颜色参数:
setLights的第一个参数是灯光颜色,不能设为0,需指定有效颜色值(如红色Color.RED)。 - 确保通道重要性足够:通道重要性建议设为
IMPORTANCE_HIGH,确保通知能触发震动和灯光(IMPORTANCE_DEFAULT也可,但部分设备可能限制)。
修正后的完整代码:
private fun sendNotification(messageBody: String?) { val intent = Intent(this, HomeActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) // Android 12+ 需使用 FLAG_IMMUTABLE 或 FLAG_MUTABLE val pendingIntentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT } else { PendingIntent.FLAG_ONE_SHOT } val pendingIntent = PendingIntent.getActivity( this, 0, intent, pendingIntentFlags ) val channelId = "my_channel_id" val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(applicationContext, channelId) .setAutoCancel(true) .setSmallIcon(R.drawable.splash_icon) .setContentText(messageBody) .setContentTitle("通知标题") // 替换为你的实际通知标题 .setContentIntent(pendingIntent) .setSound(defaultSoundUri) .setVibrate(longArrayOf(1000, 1000, 1000, 1000)) .setLights(Color.RED, 2000, 500) // 设置有效LED颜色 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val vibrationPattern = longArrayOf(1000, 1000, 1000, 1000) val channel = NotificationChannel( channelId, "应用通知", NotificationManager.IMPORTANCE_HIGH ).apply { description = "接收FCM通知的专用通道" setSound(defaultSoundUri, AudioAttributes.DEFAULT_NOTIFICATION) enableVibration(true) setVibrationPattern(vibrationPattern) enableLights(true) lightColor = Color.RED } notificationManager.createNotificationChannel(channel) } notificationManager.notify(0, notificationBuilder.build()) }
额外注意事项:
- 通知通道一旦创建,后续修改属性不会生效,若之前已创建过同名通道,需卸载重装应用或修改
channelId重新创建通道。 - 部分设备可能有系统级的通知权限限制,需确保应用已获得
POST_NOTIFICATIONS权限(Android 13+),且系统设置中允许该应用的震动和LED通知。
内容的提问来源于stack exchange,提问作者Manisha Saini
相关产品推荐
相关产品推荐

