如何修复应用后台休眠1分钟后无法接收Firebase FCM推送通知的问题
修复方案
1. 修正FCM推送优先级配置(Node.js端修改)
你当前将priority参数放在data字段内是无效的,FCM的系统级优先级需要在payload外层的android配置项中声明,只有高优先级推送才能在设备Doze休眠状态下被及时送达。修改后代码如下:
if(notification_state=="message"){ const payload = { data:{ title : `${username}`, body : `${last_message}`, userIDvisited : from_user_id, state_app:state_app, notification_state:notification_state }, android: { priority: "high", ttl: 86400 // 消息有效期,单位为秒,可按需调整 } }; return admin.messaging().sendToDevice(token_id,payload).then(response => { console.log('this was the notification Feature '); }); }
2. 主动申请忽略电池优化权限
你已经在Manifest中声明了REQUEST_IGNORE_BATTERY_OPTIMIZATIONS权限,但需要主动触发用户授权才能生效,在应用主Activity的初始化逻辑中添加以下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { String packageName = getPackageName(); PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); if (!pm.isIgnoringBatteryOptimizations(packageName)) { Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent); } }
3. 修正Notify服务中的异常逻辑
- 移除每次收到通知就删除所有通知通道的代码,该操作会导致用户自定义的通知权限被重置,还可能触发系统的反恶意行为判定
- 修正WakeLock使用逻辑,添加超时自动释放避免异常耗电
- 适配Android 12以上的PendingIntent要求,新增
FLAG_IMMUTABLE标识,避免高版本系统抛出异常 - 废弃已淘汰的
KeyguardLock接口,改用通知通道的锁屏可见配置即可满足亮屏展示需求
修改后的核心代码片段:
// PendingIntent 适配修改 int flags = PendingIntent.FLAG_UPDATE_CURRENT; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { flags |= PendingIntent.FLAG_IMMUTABLE; } PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, flags); // 移除删除所有通知通道的循环代码,仅在通道不存在时创建即可 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (mNotifyMgr != null && mNotifyMgr.getNotificationChannel(CHANNEL_ID) == null) { CharSequence name = "NotifyChannelWork"; String descrition = "NotifyChannelDescWork"; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH); channel.setDescription(descrition); channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); channel.setSound(soundUri, new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setLegacyStreamType(AudioManager.STREAM_RING) .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build()); mNotifyMgr.createNotificationChannel(channel); } } // WakeLock 修改,添加3秒超时自动释放 PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag"); wakeLock.acquire(3000L); // 删除KeyguardLock相关的废弃代码,不需要额外操作即可通过通知通道配置在锁屏展示
4. 国内厂商定制系统适配
小米、华为、OPPO、vivo等国内厂商都有独立的后台进程管理策略,即使通过了系统的电池优化授权,也需要引导用户手动开启应用的「自启动权限」「后台活动权限」,才能保证推送稳定送达。你可以在设置页添加引导入口,跳转至对应厂商的权限设置页。
内容的提问来源于stack exchange,提问作者El mansouri Ibrahim
相关产品推荐
相关产品推荐

