Android: 在显示通知之前运行代码以过滤消息的Firebase云消息传递
创始人
2024-10-06 03:00:38
0

要在显示通知之前运行代码以过滤Firebase云消息传递中的消息,可以使用Firebase Cloud Messaging (FCM) 的自定义通知处理程序。以下是一个示例解决方案:

  1. 创建一个继承自 FirebaseMessagingService 的服务类:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // 在此处运行代码以过滤消息
        
        // 调用默认的通知处理程序来显示通知
        super.onMessageReceived(remoteMessage);
    }
}
  1. 在 AndroidManifest.xml 文件中注册服务类:

    
        
    

  1. 在 MyFirebaseMessagingService 的 onMessageReceived 方法中添加代码以过滤消息。可以使用 remoteMessage 对象来访问消息的内容和元数据。根据你的需求,可以通过检查消息的标题、正文、数据字段等来决定是否显示通知。
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // 获取消息的标题和正文
    String title = remoteMessage.getNotification().getTitle();
    String body = remoteMessage.getNotification().getBody();
    
    // 获取消息的数据字段
    Map data = remoteMessage.getData();
    
    // 示例过滤逻辑:只显示标题包含关键字 "important" 的通知
    if (title != null && title.toLowerCase().contains("important")) {
        // 创建并显示通知
        showNotification(title, body);
    }
    
    // 调用默认的通知处理程序来显示通知
    super.onMessageReceived(remoteMessage);
}

private void showNotification(String title, String body) {
    // 创建通知的意图
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    // 创建通知
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
    
    // 显示通知
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, builder.build());
}

在这个示例中,我们只显示标题包含关键字 "important" 的通知。你可以根据自己的需求来修改过滤逻辑。

请确保将上述代码与你的项目中的正确包名和资源文件对应起来,并在 AndroidManifest.xml 文件中设置正确的通知渠道 (channel)。

相关内容

热门资讯

第2分钟辅助!wepoker挂... 第2分钟辅助!wepoker挂,wpk透视辅助,手册教程(的确有挂)wpk透视辅助透视方法中分为三种...
第7分钟辅助!wepokerp... 第7分钟辅助!wepokerplus到底是挂了吗,sohoopoker辅助,指南书教程(有挂攻略)1...
八分钟辅助!aapoker破解... 八分钟辅助!aapoker破解侠是真的吗,aapoker怎么设置提高好牌几率,窍门教程(有挂透视)1...
第五分钟辅助!wepoker数... 第五分钟辅助!wepoker数据分析,wpk有那种辅助吗,练习教程(有挂细节)1、玩家可以在wpk有...
4分钟辅助!hhpoker辅助... 4分钟辅助!hhpoker辅助挂下载,hhpoker德州牛仔视频,诀窍教程(有挂神器)1、hhpok...
第3分钟辅助!wepoker祈... 第3分钟辅助!wepoker祈福有用吗,pokeplus脚本,绝活儿教程(真的有挂)1、起透看视 w...
第六分钟辅助!werplan脚... 第六分钟辅助!werplan脚本,aapoker怎么控制牌,技法教程(真的有挂)aapoker怎么控...
第六分钟辅助!德普之星怎么开辅... 第六分钟辅助!德普之星怎么开辅助,德州局脚本,讲义教程(有挂教学)亲,关键说明,德普之星怎么开辅助透...
一分钟辅助!hhpoker是真... 一分钟辅助!hhpoker是真的还是假的,红龙poker辅助平台,方式教程(有挂秘籍)1、hhpok...
第三分钟辅助!哈糖大菠萝万能挂... 第三分钟辅助!哈糖大菠萝万能挂,hhpoker的辅助是真的吗,资料教程(有挂方式)1、hhpoker...