user5803705
user5803705

Reputation:

Android/Firebase - Check to see if you are subscribed to topic

I am wondering if there is a way to test to see if you are subscribed to a topic on the android side of things.

Basically, I am HOPING that all devices will subscribe to a topic during their installation, when the token is first obtained by the device. However, there is always a chance that the device fails to subscribe. The FCM registration token should be installed on the device for a long time, and thus, the onTokenRefresh() method shouldn't be called again without clearing data, uninstall/reinstall, etc.

My idea was to test to see if the device is subscribed to a topic in my MainActivity, and if not, then try to subscribe again. If it fails to subscribe, then get a new token and try again, etc.

    @Override
    public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.e(TAG, "Refreshed token: " + refreshedToken);

    // Subscribe to a topic
    Log.e(TAG, "Subscribing to topic");
    FirebaseMessaging.getInstance().subscribeToTopic("test");

So, I can subscribe and unsubscribe, but how do I check if the device is subscribed to a topic? I did my fair share of googling, and couldn't find anything, unfortunately.

I would greatly appreciate any/all assistance. Thanks!

Upvotes: 15

Views: 16308

Answers (2)

Marlo Kesser
Marlo Kesser

Reputation: 31

Actually this can be done by using this api: https://developers.google.com/instance-id/reference/server#get_information_about_app_instances

As IID_TOKEN you need the FCM token and in the header you have to pass Authentication: key=YOUR_SERVER_KEY. You can find the server key as described here: Firebase messaging, where to get Server Key?.

Don't forget to include details=true as query parameter in the url, otherwise the topics won't be included in the response.

I would recommend writing a Cloud Function to encapsulate it, so you don't deploy your server key to the client.

Upvotes: 3

AL.
AL.

Reputation: 37798

There is currently no way to check on the client side if they are subscribed to a topic.

The behavior for subscribeToTopic is it would immediately subscribe to the specified topic, if it fails, it would retry on it's own (unless your app was killed). See my answer here.

I think that forcing the onTokenRefresh call just to make sure that subscribeToTopic is too much. You could simply just call it in your initial activity if you want, that way, everytime the app starts, it sends the subscription request.

Upvotes: 12

Related Questions