Android: Subscribe to Firebase Cloud Messaging(FCM) Topic

VSB picture VSB · Oct 15, 2016 · Viewed 25k times · Source

According to Firebase cloud messaging documentation, for subscribing a user to a topic I need to call

FirebaseMessaging.getInstance().subscribeToTopic("news");
  1. In my application, I need all users to be subscribed to my cloud messaging topic. Since return value is void, the question is how can I understand that subscription was successful?
  2. Is it a bad practice to call subscribeToTopic each time my application starts?

Answer

AL. picture AL. · Oct 15, 2016

1. How can I understand that subscription was successful?

Edit:

You could now check if subscription is successful by adding addOnSuccessListener()

FirebaseMessaging.getInstance().subscribeToTopic("news").addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_LONG).show();
        }
    });

Original:

There is nothing explicitly mentioned in the docs about a response received when the subscription is successful.

However, if you need to mandate all of your users to be subscribed to a specific topic, you should call the subscribeToTopic on your app's first install. This will most likely make sure that there is a connection to the internet (since it's probably been downloaded and installed via the Play Store) and the subscription successful.

However, if you want to make sure, you can also handle he checking via your own App Server. As mentioned in the docs:

You can take advantage of Instance ID APIs to perform basic topic management tasks from the server side. Given the registration token(s) of client app instances, you can do the following:

Check through the registration tokens, if they haven't been successfully subsribed to your topic, send a notification to it where it will trigger your client app to call subscribeToTopic.