Firebase 云消息推送和应用内通知

Firebase Cloud Messaging Push and In-app notifications

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

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

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
}

我可以这样写代码吗?

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

  1. 您可以使用房间数据库。您保存所有通知,然后在片段中显示它们。如果片段已经显示,您可以使用 broadcastReceiver 立即发送和显示。 Room
  2. FCM 令牌创建一次。在以下情况下,注册令牌可能会更改:
    • 应用程序删除实例 ID
    • 该应用已在新设备上恢复
    • 用户uninstalls/reinstall应用程序
    • 用户清除应用数据。

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

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();

        }
    });