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
相关产品推荐
相关产品推荐

