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

Android Firebase如何实现仅向付费用户推送通知

FCM定向推送特定用户群体实现方案

方案1:客户端本地过滤(适配你当前存储付费标识到SharedPreferences的场景,快速落地)

  • 推送时在FCM消息的data字段携带自定义参数target_user_type,取值可设为paid(仅对付费用户)、free(仅对免费用户)、all(全部用户)
  • 在onMessageReceived回调中先读取本地SharedPreferences的付费标识,和推送携带的目标用户类型做匹配,仅匹配成功时才弹出通知
    修改后的服务类代码如下:
public class MyMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        // 读取本地存储的付费用户标识,替换为你自己的SP文件名和对应key
        SharedPreferences sp = getSharedPreferences("app_config", MODE_PRIVATE);
        boolean isPaidUser = sp.getBoolean("is_paid_user", false);
        
        // 获取推送携带的目标用户类型参数
        String targetType = remoteMessage.getData().get("target_user_type");
        boolean shouldShowNotify = false;
        
        // 匹配用户身份
        if ("all".equals(targetType)) {
            shouldShowNotify = true;
        } else if ("paid".equals(targetType) && isPaidUser) {
            shouldShowNotify = true;
        } else if ("free".equals(targetType) && !isPaidUser) {
            shouldShowNotify = true;
        }
        
        // 匹配通过且推送有通知内容时才弹窗
        if (shouldShowNotify && remoteMessage.getNotification() != null) {
            showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    public void showNotification(String title,String message){
        NotificationCompat.Builder builder=new NotificationCompat.Builder(this,"MyNotifications")
                .setContentTitle(title)
                .setSmallIcon(R.mipmap.ic_launcher) // 替换为你的应用图标资源
                .setAutoCancel(true)
                .setContentText(message);

        NotificationManagerCompat manager= NotificationManagerCompat.from(this);
        manager.notify(999,builder.build());
    }
}

方案2:FCM主题订阅定向推送(更高效,生产环境推荐)

  • 无需客户端做消息过滤,在用户付费状态变更时同步更新FCM主题订阅即可:付费用户订阅paid_user主题,免费用户取消订阅该主题
  • 推送时直接指定发送到paid_user主题,只有订阅了该主题的设备能收到消息
    订阅/取消订阅代码示例:
// 付费成功后调用,订阅付费用户专属主题
FirebaseMessaging.getInstance().subscribeToTopic("paid_user");

// 会员到期后调用,取消订阅付费用户主题
FirebaseMessaging.getInstance().unsubscribeFromTopic("paid_user");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:57:03