【问题标题】:Firebase Cloud Messaging Push and In-app notificationsFirebase 云消息推送和应用内通知
【发布时间】:2020-07-08 08:50:42
【问题描述】:

现在我可以从 Firebase 控制台发送测试消息并在我的手机中收到推送通知。我现在对生成应用内通知有一些疑问。这是我目前的布局。

我也希望推送通知在我的应用中显示为应用内通知。处理消息的唯一类是 MyFirebaseMessagingService 类,其中包括一个 notificationHelper 以帮助构建通知。如何将来自MyFirebaseMessagingService 的消息信息传递到我现在拥有的通知片段?我是否需要将信息存储在本地文件中,然后从本地文件中检索信息以再次在通知片段中使用?在这种情况下,最好的方法是什么?

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();
            NotificationHelper.displayNotification(getApplicationContext(), title, body);
        }
    }
}

另一个琐碎的问题是关于 FCM 令牌问题。我已经创建了 FCM 令牌。如何让应用程序检查是否已生成令牌以防止每次启动应用程序时都生成令牌?

if(instanceIdResult.getToken() == null)
{
   //generate token
}

我可以这样写代码吗?

【问题讨论】:

    标签: android firebase firebase-cloud-messaging android-notifications


    【解决方案1】:
    1. 您可以使用房间数据库。您保存所有通知,然后在片段中显示它们。如果片段已经显示,您可以使用广播接收器立即发送和显示。 Room
    2. FCM 令牌创建一次。注册令牌可能会在以下情况下更改:
      • 应用删除实例 ID
      • 应用已在新设备上恢复
      • 用户卸载/重新安装应用程序
      • 用户清除应用数据。

    您可以像这样检索当前令牌:

    FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }
    
                String token = task.getResult().getToken();
    
            }
        });
    

    【讨论】:

      【解决方案2】:

      您可以使用sharedpreferences 来存储您收到的通知数量,当您的应用打开时会在通知上显示该数量,如果用户阅读它们,则重置计数器。你也可以存储令牌

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 2020-06-05
        • 2017-10-04
        • 1970-01-01
        • 2020-08-14
        • 2019-08-25
        相关资源
        最近更新 更多