Ray Jasson
Ray Jasson

Reputation: 451

Firebase Cloud Messaging Push and In-app notifications

Now I can send test message from Firebase Console and get a push notification in my phone. I have some queries about generating in-app notification right now. This is my current layout.

enter image description here

I want the push notifications to appear as in-app notifications in my app too. The only class handling the message is MyFirebaseMessagingService class which includes a notificationHelper to help build the notification. How do I pass the message information from MyFirebaseMessagingService to the Notification Fragment I have now? Do I need to store the information in a local file then retrieve the information from the local file to be used in Notification Fragment again? What is the best approach in this case?

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

Another trivial question is about the FCM token issue. I have already created a FCM token. How do I make the app to check if a token has been generated to prevent the token be generated every time I launch the app?

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

Can I write the code like this?

Upvotes: 1

Views: 384

Answers (2)

Kasım Özdemir
Kasım Özdemir

Reputation: 5634

  1. You can use room database. You save all the notifications and then show them in the fragment. If the fragment is already show, you can send and show instantly with broadcastReceiver. Room
  2. FCM token is created once. The registration token may change when:
    • The app deletes Instance ID
    • The app is restored on a new device
    • The user uninstalls/reinstall the app
    • The user clears app data.

You can retrieve the current token like this:

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

        }
    });

Upvotes: 2

Alireza Sharifi
Alireza Sharifi

Reputation: 1162

you can use sharedpreferences to store number of notifications you get and when yor app opens show the number on notification and if user read them reset the counter . also you can store the token too

Upvotes: 1

Related Questions