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

为何Firebase推送通知仅在Android应用关闭时生效?

Firebase推送通知:应用前台无法接收是否正常?

这不是正常情况,Firebase推送通知在应用前台、后台、关闭状态下都应该能被接收,只是不同状态下的处理逻辑有区别:

  • 应用关闭/后台时,系统会自动将通知展示在通知栏
  • 应用前台时,通知不会自动弹出,需要你在自定义的FirebaseNotificationService里手动实现展示逻辑

你的配置已经注册了监听com.google.firebase.MESSAGING_EVENT的服务,但问题大概率出在没重写onMessageReceived方法来处理前台消息。你需要在FirebaseNotificationService中添加以下核心逻辑:

public class FirebaseNotificationService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // 提取推送的标题和内容
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();
        
        // 构建前台通知并展示
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "your_notification_channel_id")
                .setSmallIcon(R.drawable.ic_notification_icon)
                .setContentTitle(title)
                .setContentText(body)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        // Android 8.0+ 必须创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("your_notification_channel_id", "通知渠道名称", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        // 触发通知展示
        notificationManager.notify(1, builder.build());
    }
}

额外注意事项:

  • 确保FirebaseNotificationService正确继承自FirebaseMessagingService
  • Android 8.0及以上版本必须提前创建通知渠道,否则通知无法正常显示
  • 如果推送的是数据消息(而非带通知体的消息),无论应用处于什么状态,都会直接触发onMessageReceived,需自行处理展示逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:20:39