Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get receiver's device token to send notification in Firebase

So I'm learning on how to use firebase to send device-to-device notifications and I saw this answer to send the notification and it seemed straight forward. Now, I know to get the sender's token, it should look like this:-

FirebaseInstanceId.getInstance().getToken();

but I can't for the life of me seem to find how to get the other needed token. how do I get the receiver's token so that the message goes straight to them?

like image 233
Aria Avatar asked Mar 07 '23 00:03

Aria


1 Answers

It is the same also for the receiver.

From the docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token by extending FirebaseInstanceIdService.

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.

So to get the token of the any device(reciever or sender) you need use this:

  FirebaseInstanceId.getInstance().getToken();

The above will generate a token for you, its better to execute the code when the user installs the app on his device(at the beginning).

Now that a token for the receiver is generated, the next thing to do is to store the token in your database to be able to use the token and send a notification to that specific user as there is no other way for you to know the token of the other device.

To store it simply do this:

 String token=FirebaseInstanceId.getInstance().getToken();
 DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Tokens");
 ref.child(user.getUid()).setValue(token);

Now this is just an example, you can store it as you want. I used the user id as it is easy to obtain since the user is the one that will be using his phone.

This way you will have the token of the receiver then you can send a notification to that specific token using cloud functions if you want.

For more info: https://firebase.google.com/docs/cloud-messaging/admin/send-messages#send_to_individual_devices

The token is being sent to the device, so the token is related to the device. Now to get the uid, then the user needs to be logged in and authenticated and then you can use the uid in the database.

If the user has many devices, then you need the token of other devices also. Again it is related to the device not to the user.

But you use the uid in the database to know this token is for who.

Summary:

  1. Token is related to device not user
  2. userid is just used to identify the user in db
  3. If user has multiple devices, then you need to generate the token of each device(same as above code).
  4. By database, I meant firebase-database
like image 78
Peter Haddad Avatar answered Mar 16 '23 16:03

Peter Haddad