Get receiver's device token to send notification in Firebase

后端 未结 1 999
悲&欢浪女
悲&欢浪女 2021-02-10 13:50

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

相关标签:
1条回答
  • 2021-02-10 14:43

    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
    0 讨论(0)
提交回复
热议问题