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

FCM通知引发应用崩溃、Android 13通知无法显示问题求助

解决FCM通知崩溃与Android 13通知不显示的方案

一、修复通知崩溃问题

1. 处理消息数据空指针

message.data中的字段可能为空,直接赋值会触发空指针异常,需添加非空兜底逻辑:

val title = message.data.getOrDefault("title", "系统通知")
val content = message.data.getOrDefault("message", "您有一条新消息")
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle(title)
    .setContentText(content)
    // 其他配置项...

2. 更新PendingIntent的Flag(适配Android 12+)

Android 12及以上版本要求PendingIntent必须指定FLAG_IMMUTABLE或FLAG_MUTABLE,仅用FLAG_ONE_SHOT会触发SecurityException:

val pendingIntentFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
} else {
    PendingIntent.FLAG_ONE_SHOT
}
val pendingIntent = PendingIntent.getActivity(this, 0, intent, pendingIntentFlag)

3. 初始化SharedPreferences

companion object中的sharedPref未初始化,调用token属性时会空指针,在Service的onCreate中完成初始化:

override fun onCreate() {
    super.onCreate()
    sharedPref = getSharedPreferences("FCM_TOKEN_PREF", Context.MODE_PRIVATE)
}

4. 添加异常捕获

在onMessageReceived中用try-catch包裹核心逻辑,避免崩溃并记录错误日志:

override fun onMessageReceived(message: RemoteMessage) {
    super.onMessageReceived(message)
    try {
        // 原有的通知构建与发送逻辑
    } catch (e: Exception) {
        Log.e("FirebaseService", "通知处理失败", e)
    }
}

二、修复Android 13通知不显示问题

1. 申请POST_NOTIFICATIONS权限

Android 13(API 33)及以上必须显式申请通知权限:

  • 在AndroidManifest.xml中声明权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  • 在主Activity中动态请求权限:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1001)
    }
}

2. 检查通知图标合规性

Android 8.0+要求通知图标必须是透明背景的单色图标,如果R.drawable.notification_foreground不符合规范,会导致通知不显示或显示系统默认图标,建议替换为符合要求的图标。

3. 确认通知渠道配置

在AndroidManifest.xml中添加FCM默认渠道的元数据配置,增强兼容性:

<meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="my_channel" />

三、其他排查方向

  • 升级Firebase依赖到最新版本,旧版本可能存在适配漏洞;
  • 检查测试设备的系统设置:确认应用的通知权限已开启;
  • 通过Firebase控制台发送测试消息,验证onMessageReceived是否被正常触发;
  • 排查厂商后台限制:部分国产ROM会限制后台Service运行,需将应用加入白名单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 21:17:07