Firebase Cloud Messaging - Handling logout











up vote
31
down vote

favorite
11












How do I handle situation, when user logs out of my application and I no longer want him to receive notifications to the device.



I tried



FirebaseInstanceId.getInstance().deleteToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


But I still receive the notifications to my device's registration_id.



I also made sure that this is the token I should delete:



FirebaseInstanceId.getInstance().getToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


or simply FirebaseInstanceId.getInstance().getToken()).



I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).



I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack. And also there's this answer which states that it shouldn't be done, but it proposes deleting the token which apparently doesn't work.



So what is the right method to handle this?










share|improve this question




























    up vote
    31
    down vote

    favorite
    11












    How do I handle situation, when user logs out of my application and I no longer want him to receive notifications to the device.



    I tried



    FirebaseInstanceId.getInstance().deleteToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


    But I still receive the notifications to my device's registration_id.



    I also made sure that this is the token I should delete:



    FirebaseInstanceId.getInstance().getToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


    or simply FirebaseInstanceId.getInstance().getToken()).



    I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).



    I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack. And also there's this answer which states that it shouldn't be done, but it proposes deleting the token which apparently doesn't work.



    So what is the right method to handle this?










    share|improve this question


























      up vote
      31
      down vote

      favorite
      11









      up vote
      31
      down vote

      favorite
      11






      11





      How do I handle situation, when user logs out of my application and I no longer want him to receive notifications to the device.



      I tried



      FirebaseInstanceId.getInstance().deleteToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


      But I still receive the notifications to my device's registration_id.



      I also made sure that this is the token I should delete:



      FirebaseInstanceId.getInstance().getToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


      or simply FirebaseInstanceId.getInstance().getToken()).



      I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).



      I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack. And also there's this answer which states that it shouldn't be done, but it proposes deleting the token which apparently doesn't work.



      So what is the right method to handle this?










      share|improve this question















      How do I handle situation, when user logs out of my application and I no longer want him to receive notifications to the device.



      I tried



      FirebaseInstanceId.getInstance().deleteToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


      But I still receive the notifications to my device's registration_id.



      I also made sure that this is the token I should delete:



      FirebaseInstanceId.getInstance().getToken(FirebaseInstanceId.getInstance().getId(), FirebaseMessaging.INSTANCE_ID_SCOPE)


      or simply FirebaseInstanceId.getInstance().getToken()).



      I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).



      I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack. And also there's this answer which states that it shouldn't be done, but it proposes deleting the token which apparently doesn't work.



      So what is the right method to handle this?







      android firebase firebase-cloud-messaging






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '17 at 11:46









      Community

      11




      11










      asked Apr 3 '17 at 19:56









      Michał K

      6,44274279




      6,44274279
























          5 Answers
          5






          active

          oldest

          votes

















          up vote
          27
          down vote



          accepted










          Okay. So I managed to do some testing and have concluded the following:





          1. deleteToken() is the counterpart of getToken(String, String), but not for getToken().


          It only works if the Sender ID you are passing is a different Sender ID (not the same ID that can be seen in your google-services.json). For example, you want to allow a different Server to send to your app, you call getToken("THEIR_SENDER_ID", "FCM") to give them authorization to send to your app. This will return a different registration token that corresponds only to that specific sender.



          In the future, if you chose to remove their authorization to send to your app, you'll then have to make use of deleteToken("THEIR_SENDER_ID", "FCM"). This will invalidate the corresponding token, and when the Sender attempts to send a message, as the intended behavior, they will receive a NotRegistered error.




          1. In order to delete the token for your own Sender, the correct handling is to use deleteInstanceId().


          Special mentioning this answer by @Prince, specifically the code sample for helping me with this.



          As @MichałK already doing in his post, after calling the deleteInstanceId(), getToken() should be called in order to send a request for a new token. However, you don't have to call it the second time. So long as onTokenRefresh() onNewToken() is implemented, it should automatically trigger providing you the new token.



          For short, deleteInstanceId() > getToken() > check onTokenRefresh() onNewToken().



          Note: Calling deleteInstanceId() will not only delete the token for your own app. It will delete all topic subscriptions and all other tokens associated with the app instance.





          Are you positive you're calling deleteToken() properly? The value for audience should be (also seen from my answer that you linked) is "set to the app server's sender ID". You're passing the getId() value which is not the same as the Sender ID (it contains the app instance id value). Also, how are you sending the message (App Server or Notifications Console)?



          getToken() and getToken(String, String) returns different tokens. See my answer here.




          I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).




          It's probably because the first time you're calling the getToken(), it's still being generated. It's just the intended behavior.




          I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack.




          Not really. It's how you'll get the new generated (provided that it is already generated) token. So I think it's fine.






          share|improve this answer























          • This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
            – Michał K
            Apr 4 '17 at 4:37










          • As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
            – Michał K
            Apr 4 '17 at 4:38










          • I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
            – AL.
            Apr 4 '17 at 6:22










          • Thanks, I would really appreciate that.
            – Michał K
            Apr 4 '17 at 6:25






          • 2




            Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
            – Michał K
            Apr 4 '17 at 9:26


















          up vote
          12
          down vote













          I was working on the same problem, when I had done my logout() from my application. But the problem was that after logging out, I was still getting push notifications from Firebase. I tried to delete the Firebase token. But after deleting the token in my logout() method, it is null when I query for it in my login() method. After working 2 days I finally got a solution.





          1. In your logout() method, delete the Firebase token in the background because you can not delete Firebase token from the main thread



            new AsyncTask<Void,Void,Void>() {
            @Override
            protected Void doInBackground(Void... params) {
            try
            {
            FirebaseInstanceId.getInstance().deleteInstanceId();
            } catch (IOException e)
            {
            e.printStackTrace();
            }
            return null;
            }

            @Override
            protected void onPostExecute(Void result) {
            // Call your Activity where you want to land after log out
            }
            }.execute();



          2. In your login() method, generate the Firebase token again.



            new AsyncTask<Void,Void,Void>() {
            @Override
            protected Void doInBackground(Void... params) {
            String token = FirebaseInstanceId.getInstance().getToken();
            // Used to get firebase token until its null so it will save you from null pointer exeption
            while(token == null) {
            token = FirebaseInstanceId.getInstance().getToken();
            }
            return null;
            }
            @Override
            protected void onPostExecute(Void result) {
            }
            }.execute();







          share|improve this answer






























            up vote
            5
            down vote













            I did a brief research on what would be the most elegant solution to get back the full control (subscribe and unsubscribe to FCM) as before. Enable and disable the FCM after the user logged in or out.



            Step 1. - Prevent auto initialization



            Firebase now handle the InstanceID and everything else which need to generate a registration token. First of all you need to prevent auto initialization. Based on the official set-up documentation you need to add these meta-data values to your AndroidManifest.xml:



            <?xml version="1.0" encoding="utf-8"?>
            <application>

            <!-- FCM: Disable auto-init -->
            <meta-data android:name="firebase_messaging_auto_init_enabled"
            android:value="false" />
            <meta-data android:name="firebase_analytics_collection_enabled"
            android:value="false" />

            <!-- FCM: Receive token and messages -->
            <service android:name=".FCMService">
            <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
            </service>

            </application>


            Now you disabled the automatic token request process. At the same time you have an option to enable it again at runtime by code.



            Step 2. - Implement enableFCM() and disableFCM() functions



            If you enable the auto initialization again then you received a new token immediately, so this is a perfect way to implement the enableFCM() method.
            All subscribe information assigned to InstanceID, so when you delete it then initiate to unsubscribe all topic. On this way you able to implement disableFCM() method, just turn back off auto-init before you delete it.



            public class FCMHandler {

            public void enableFCM(){
            // Enable FCM via enable Auto-init service which generate new token and receive in FCMService
            FirebaseMessaging.getInstance().setAutoInitEnabled(true);
            }

            public void disableFCM(){
            // Disable auto init
            FirebaseMessaging.getInstance().setAutoInitEnabled(false);
            new Thread(() -> {
            try {
            // Remove InstanceID initiate to unsubscribe all topic
            // TODO: May be a better way to use FirebaseMessaging.getInstance().unsubscribeFromTopic()
            FirebaseInstanceId.getInstance().deleteInstanceId();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }).start();
            }

            }


            Step 3. - FCMService implementation - token and message receiving



            In the last step you need to receive the new token and send direct to your server.
            Other hand you'll receive your data message and just do it what you want.



            public class FCMService extends FirebaseMessagingService {

            @Override
            public void onNewToken(String token) {
            super.onNewToken(token);
            // TODO: send your new token to the server
            }

            @Override
            public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
            String from = remoteMessage.getFrom();
            Map data = remoteMessage.getData();
            if (data != null) {
            // TODO: handle your message and data
            sendMessageNotification(message, messageId);
            }
            }

            private void sendMessageNotification(String msg, long messageId) {
            // TODO: show notification using NotificationCompat
            }
            }


            I think this solution is clear, simple and transparent. I tested in a production environment and it's works. I hope it was helpful.






            share|improve this answer





















            • Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
              – Hey You
              Oct 24 at 3:16












            • Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
              – János Sicz-Mesziár
              Nov 11 at 19:54


















            up vote
            2
            down vote













            I know I am late for the party. deleteInstanceId() should be called from the background thread since it's a blocking call. Just check the method deleteInstanceId() in FirebaseInstanceId() class.



            @WorkerThread
            public void deleteInstanceId() throws IOException {
            if (Looper.getMainLooper() == Looper.myLooper()) {
            throw new IOException("MAIN_THREAD");
            } else {
            String var1 = zzh();
            this.zza(this.zzal.deleteInstanceId(var1));
            this.zzl();
            }
            }


            You can start an IntentService to delete the instance id and the data associated with it.






            share|improve this answer





















            • This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
              – Michał K
              Jul 26 at 6:21


















            up vote
            0
            down vote













            Since the getToken() is deprecated, use getInstanceId() to regenerate new token instead. It has same effect.



            public static void resetInstanceId() {
            new Thread(new Runnable() {
            @Override
            public void run() {
            try {
            FirebaseInstanceId.getInstance().deleteInstanceId();
            FirebaseInstanceId.getInstance().getInstanceId();
            Helper.log(TAG, "InstanceId removed and regenerated.");
            } catch (IOException e) {
            e.printStackTrace();
            }
            }
            }).start();
            }





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43193215%2ffirebase-cloud-messaging-handling-logout%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              27
              down vote



              accepted










              Okay. So I managed to do some testing and have concluded the following:





              1. deleteToken() is the counterpart of getToken(String, String), but not for getToken().


              It only works if the Sender ID you are passing is a different Sender ID (not the same ID that can be seen in your google-services.json). For example, you want to allow a different Server to send to your app, you call getToken("THEIR_SENDER_ID", "FCM") to give them authorization to send to your app. This will return a different registration token that corresponds only to that specific sender.



              In the future, if you chose to remove their authorization to send to your app, you'll then have to make use of deleteToken("THEIR_SENDER_ID", "FCM"). This will invalidate the corresponding token, and when the Sender attempts to send a message, as the intended behavior, they will receive a NotRegistered error.




              1. In order to delete the token for your own Sender, the correct handling is to use deleteInstanceId().


              Special mentioning this answer by @Prince, specifically the code sample for helping me with this.



              As @MichałK already doing in his post, after calling the deleteInstanceId(), getToken() should be called in order to send a request for a new token. However, you don't have to call it the second time. So long as onTokenRefresh() onNewToken() is implemented, it should automatically trigger providing you the new token.



              For short, deleteInstanceId() > getToken() > check onTokenRefresh() onNewToken().



              Note: Calling deleteInstanceId() will not only delete the token for your own app. It will delete all topic subscriptions and all other tokens associated with the app instance.





              Are you positive you're calling deleteToken() properly? The value for audience should be (also seen from my answer that you linked) is "set to the app server's sender ID". You're passing the getId() value which is not the same as the Sender ID (it contains the app instance id value). Also, how are you sending the message (App Server or Notifications Console)?



              getToken() and getToken(String, String) returns different tokens. See my answer here.




              I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).




              It's probably because the first time you're calling the getToken(), it's still being generated. It's just the intended behavior.




              I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack.




              Not really. It's how you'll get the new generated (provided that it is already generated) token. So I think it's fine.






              share|improve this answer























              • This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
                – Michał K
                Apr 4 '17 at 4:37










              • As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
                – Michał K
                Apr 4 '17 at 4:38










              • I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
                – AL.
                Apr 4 '17 at 6:22










              • Thanks, I would really appreciate that.
                – Michał K
                Apr 4 '17 at 6:25






              • 2




                Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
                – Michał K
                Apr 4 '17 at 9:26















              up vote
              27
              down vote



              accepted










              Okay. So I managed to do some testing and have concluded the following:





              1. deleteToken() is the counterpart of getToken(String, String), but not for getToken().


              It only works if the Sender ID you are passing is a different Sender ID (not the same ID that can be seen in your google-services.json). For example, you want to allow a different Server to send to your app, you call getToken("THEIR_SENDER_ID", "FCM") to give them authorization to send to your app. This will return a different registration token that corresponds only to that specific sender.



              In the future, if you chose to remove their authorization to send to your app, you'll then have to make use of deleteToken("THEIR_SENDER_ID", "FCM"). This will invalidate the corresponding token, and when the Sender attempts to send a message, as the intended behavior, they will receive a NotRegistered error.




              1. In order to delete the token for your own Sender, the correct handling is to use deleteInstanceId().


              Special mentioning this answer by @Prince, specifically the code sample for helping me with this.



              As @MichałK already doing in his post, after calling the deleteInstanceId(), getToken() should be called in order to send a request for a new token. However, you don't have to call it the second time. So long as onTokenRefresh() onNewToken() is implemented, it should automatically trigger providing you the new token.



              For short, deleteInstanceId() > getToken() > check onTokenRefresh() onNewToken().



              Note: Calling deleteInstanceId() will not only delete the token for your own app. It will delete all topic subscriptions and all other tokens associated with the app instance.





              Are you positive you're calling deleteToken() properly? The value for audience should be (also seen from my answer that you linked) is "set to the app server's sender ID". You're passing the getId() value which is not the same as the Sender ID (it contains the app instance id value). Also, how are you sending the message (App Server or Notifications Console)?



              getToken() and getToken(String, String) returns different tokens. See my answer here.




              I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).




              It's probably because the first time you're calling the getToken(), it's still being generated. It's just the intended behavior.




              I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack.




              Not really. It's how you'll get the new generated (provided that it is already generated) token. So I think it's fine.






              share|improve this answer























              • This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
                – Michał K
                Apr 4 '17 at 4:37










              • As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
                – Michał K
                Apr 4 '17 at 4:38










              • I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
                – AL.
                Apr 4 '17 at 6:22










              • Thanks, I would really appreciate that.
                – Michał K
                Apr 4 '17 at 6:25






              • 2




                Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
                – Michał K
                Apr 4 '17 at 9:26













              up vote
              27
              down vote



              accepted







              up vote
              27
              down vote



              accepted






              Okay. So I managed to do some testing and have concluded the following:





              1. deleteToken() is the counterpart of getToken(String, String), but not for getToken().


              It only works if the Sender ID you are passing is a different Sender ID (not the same ID that can be seen in your google-services.json). For example, you want to allow a different Server to send to your app, you call getToken("THEIR_SENDER_ID", "FCM") to give them authorization to send to your app. This will return a different registration token that corresponds only to that specific sender.



              In the future, if you chose to remove their authorization to send to your app, you'll then have to make use of deleteToken("THEIR_SENDER_ID", "FCM"). This will invalidate the corresponding token, and when the Sender attempts to send a message, as the intended behavior, they will receive a NotRegistered error.




              1. In order to delete the token for your own Sender, the correct handling is to use deleteInstanceId().


              Special mentioning this answer by @Prince, specifically the code sample for helping me with this.



              As @MichałK already doing in his post, after calling the deleteInstanceId(), getToken() should be called in order to send a request for a new token. However, you don't have to call it the second time. So long as onTokenRefresh() onNewToken() is implemented, it should automatically trigger providing you the new token.



              For short, deleteInstanceId() > getToken() > check onTokenRefresh() onNewToken().



              Note: Calling deleteInstanceId() will not only delete the token for your own app. It will delete all topic subscriptions and all other tokens associated with the app instance.





              Are you positive you're calling deleteToken() properly? The value for audience should be (also seen from my answer that you linked) is "set to the app server's sender ID". You're passing the getId() value which is not the same as the Sender ID (it contains the app instance id value). Also, how are you sending the message (App Server or Notifications Console)?



              getToken() and getToken(String, String) returns different tokens. See my answer here.




              I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).




              It's probably because the first time you're calling the getToken(), it's still being generated. It's just the intended behavior.




              I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack.




              Not really. It's how you'll get the new generated (provided that it is already generated) token. So I think it's fine.






              share|improve this answer














              Okay. So I managed to do some testing and have concluded the following:





              1. deleteToken() is the counterpart of getToken(String, String), but not for getToken().


              It only works if the Sender ID you are passing is a different Sender ID (not the same ID that can be seen in your google-services.json). For example, you want to allow a different Server to send to your app, you call getToken("THEIR_SENDER_ID", "FCM") to give them authorization to send to your app. This will return a different registration token that corresponds only to that specific sender.



              In the future, if you chose to remove their authorization to send to your app, you'll then have to make use of deleteToken("THEIR_SENDER_ID", "FCM"). This will invalidate the corresponding token, and when the Sender attempts to send a message, as the intended behavior, they will receive a NotRegistered error.




              1. In order to delete the token for your own Sender, the correct handling is to use deleteInstanceId().


              Special mentioning this answer by @Prince, specifically the code sample for helping me with this.



              As @MichałK already doing in his post, after calling the deleteInstanceId(), getToken() should be called in order to send a request for a new token. However, you don't have to call it the second time. So long as onTokenRefresh() onNewToken() is implemented, it should automatically trigger providing you the new token.



              For short, deleteInstanceId() > getToken() > check onTokenRefresh() onNewToken().



              Note: Calling deleteInstanceId() will not only delete the token for your own app. It will delete all topic subscriptions and all other tokens associated with the app instance.





              Are you positive you're calling deleteToken() properly? The value for audience should be (also seen from my answer that you linked) is "set to the app server's sender ID". You're passing the getId() value which is not the same as the Sender ID (it contains the app instance id value). Also, how are you sending the message (App Server or Notifications Console)?



              getToken() and getToken(String, String) returns different tokens. See my answer here.




              I also tried FirebaseInstanceId.getInstance().deleteInstanceId(), but then the next time I call FirebaseInstanceId.getInstance.getToken I receive null (it works on the second try).




              It's probably because the first time you're calling the getToken(), it's still being generated. It's just the intended behavior.




              I guess, after deleteInstanceId I could immediately call getToken() again, but it looks like a hack.




              Not really. It's how you'll get the new generated (provided that it is already generated) token. So I think it's fine.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 8 at 12:12

























              answered Apr 4 '17 at 3:09









              AL.

              23k753179




              23k753179












              • This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
                – Michał K
                Apr 4 '17 at 4:37










              • As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
                – Michał K
                Apr 4 '17 at 4:38










              • I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
                – AL.
                Apr 4 '17 at 6:22










              • Thanks, I would really appreciate that.
                – Michał K
                Apr 4 '17 at 6:25






              • 2




                Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
                – Michał K
                Apr 4 '17 at 9:26


















              • This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
                – Michał K
                Apr 4 '17 at 4:37










              • As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
                – Michał K
                Apr 4 '17 at 4:38










              • I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
                – AL.
                Apr 4 '17 at 6:22










              • Thanks, I would really appreciate that.
                – Michał K
                Apr 4 '17 at 6:25






              • 2




                Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
                – Michał K
                Apr 4 '17 at 9:26
















              This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
              – Michał K
              Apr 4 '17 at 4:37




              This is the only "sender id" which did not throw an error when I called getToken or deleteToken. When I used the text project id from my firebase console both methods threw. Then I used the numerical id which I found in googleservices.json and it looked like it worked. Then passed the getId() and it didn't throw either. So I I figured that's it.
              – Michał K
              Apr 4 '17 at 4:37












              As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
              – Michał K
              Apr 4 '17 at 4:38




              As for the hack, I have to call it immediately after deleteInstanceId so it returns null the first time, and then call it during login for it to work. That's why I think it's a hack.
              – Michał K
              Apr 4 '17 at 4:38












              I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
              – AL.
              Apr 4 '17 at 6:22




              I'll try and see if I can do some testing later and replicate the behavior. Will get back here if I have the time. Cheers!
              – AL.
              Apr 4 '17 at 6:22












              Thanks, I would really appreciate that.
              – Michał K
              Apr 4 '17 at 6:25




              Thanks, I would really appreciate that.
              – Michał K
              Apr 4 '17 at 6:25




              2




              2




              Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
              – Michał K
              Apr 4 '17 at 9:26




              Thank you for checking it! Honestly, I'm surprised how bad and poorly documented this API is... Will give it a spin, though, thanks!
              – Michał K
              Apr 4 '17 at 9:26












              up vote
              12
              down vote













              I was working on the same problem, when I had done my logout() from my application. But the problem was that after logging out, I was still getting push notifications from Firebase. I tried to delete the Firebase token. But after deleting the token in my logout() method, it is null when I query for it in my login() method. After working 2 days I finally got a solution.





              1. In your logout() method, delete the Firebase token in the background because you can not delete Firebase token from the main thread



                new AsyncTask<Void,Void,Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                try
                {
                FirebaseInstanceId.getInstance().deleteInstanceId();
                } catch (IOException e)
                {
                e.printStackTrace();
                }
                return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                // Call your Activity where you want to land after log out
                }
                }.execute();



              2. In your login() method, generate the Firebase token again.



                new AsyncTask<Void,Void,Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                String token = FirebaseInstanceId.getInstance().getToken();
                // Used to get firebase token until its null so it will save you from null pointer exeption
                while(token == null) {
                token = FirebaseInstanceId.getInstance().getToken();
                }
                return null;
                }
                @Override
                protected void onPostExecute(Void result) {
                }
                }.execute();







              share|improve this answer



























                up vote
                12
                down vote













                I was working on the same problem, when I had done my logout() from my application. But the problem was that after logging out, I was still getting push notifications from Firebase. I tried to delete the Firebase token. But after deleting the token in my logout() method, it is null when I query for it in my login() method. After working 2 days I finally got a solution.





                1. In your logout() method, delete the Firebase token in the background because you can not delete Firebase token from the main thread



                  new AsyncTask<Void,Void,Void>() {
                  @Override
                  protected Void doInBackground(Void... params) {
                  try
                  {
                  FirebaseInstanceId.getInstance().deleteInstanceId();
                  } catch (IOException e)
                  {
                  e.printStackTrace();
                  }
                  return null;
                  }

                  @Override
                  protected void onPostExecute(Void result) {
                  // Call your Activity where you want to land after log out
                  }
                  }.execute();



                2. In your login() method, generate the Firebase token again.



                  new AsyncTask<Void,Void,Void>() {
                  @Override
                  protected Void doInBackground(Void... params) {
                  String token = FirebaseInstanceId.getInstance().getToken();
                  // Used to get firebase token until its null so it will save you from null pointer exeption
                  while(token == null) {
                  token = FirebaseInstanceId.getInstance().getToken();
                  }
                  return null;
                  }
                  @Override
                  protected void onPostExecute(Void result) {
                  }
                  }.execute();







                share|improve this answer

























                  up vote
                  12
                  down vote










                  up vote
                  12
                  down vote









                  I was working on the same problem, when I had done my logout() from my application. But the problem was that after logging out, I was still getting push notifications from Firebase. I tried to delete the Firebase token. But after deleting the token in my logout() method, it is null when I query for it in my login() method. After working 2 days I finally got a solution.





                  1. In your logout() method, delete the Firebase token in the background because you can not delete Firebase token from the main thread



                    new AsyncTask<Void,Void,Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                    try
                    {
                    FirebaseInstanceId.getInstance().deleteInstanceId();
                    } catch (IOException e)
                    {
                    e.printStackTrace();
                    }
                    return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                    // Call your Activity where you want to land after log out
                    }
                    }.execute();



                  2. In your login() method, generate the Firebase token again.



                    new AsyncTask<Void,Void,Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                    String token = FirebaseInstanceId.getInstance().getToken();
                    // Used to get firebase token until its null so it will save you from null pointer exeption
                    while(token == null) {
                    token = FirebaseInstanceId.getInstance().getToken();
                    }
                    return null;
                    }
                    @Override
                    protected void onPostExecute(Void result) {
                    }
                    }.execute();







                  share|improve this answer














                  I was working on the same problem, when I had done my logout() from my application. But the problem was that after logging out, I was still getting push notifications from Firebase. I tried to delete the Firebase token. But after deleting the token in my logout() method, it is null when I query for it in my login() method. After working 2 days I finally got a solution.





                  1. In your logout() method, delete the Firebase token in the background because you can not delete Firebase token from the main thread



                    new AsyncTask<Void,Void,Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                    try
                    {
                    FirebaseInstanceId.getInstance().deleteInstanceId();
                    } catch (IOException e)
                    {
                    e.printStackTrace();
                    }
                    return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                    // Call your Activity where you want to land after log out
                    }
                    }.execute();



                  2. In your login() method, generate the Firebase token again.



                    new AsyncTask<Void,Void,Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                    String token = FirebaseInstanceId.getInstance().getToken();
                    // Used to get firebase token until its null so it will save you from null pointer exeption
                    while(token == null) {
                    token = FirebaseInstanceId.getInstance().getToken();
                    }
                    return null;
                    }
                    @Override
                    protected void onPostExecute(Void result) {
                    }
                    }.execute();








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 9 at 22:22









                  Sky Kelsey

                  12.9k52563




                  12.9k52563










                  answered Aug 12 '17 at 6:43









                  Sunil

                  1,61711229




                  1,61711229






















                      up vote
                      5
                      down vote













                      I did a brief research on what would be the most elegant solution to get back the full control (subscribe and unsubscribe to FCM) as before. Enable and disable the FCM after the user logged in or out.



                      Step 1. - Prevent auto initialization



                      Firebase now handle the InstanceID and everything else which need to generate a registration token. First of all you need to prevent auto initialization. Based on the official set-up documentation you need to add these meta-data values to your AndroidManifest.xml:



                      <?xml version="1.0" encoding="utf-8"?>
                      <application>

                      <!-- FCM: Disable auto-init -->
                      <meta-data android:name="firebase_messaging_auto_init_enabled"
                      android:value="false" />
                      <meta-data android:name="firebase_analytics_collection_enabled"
                      android:value="false" />

                      <!-- FCM: Receive token and messages -->
                      <service android:name=".FCMService">
                      <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                      </intent-filter>
                      </service>

                      </application>


                      Now you disabled the automatic token request process. At the same time you have an option to enable it again at runtime by code.



                      Step 2. - Implement enableFCM() and disableFCM() functions



                      If you enable the auto initialization again then you received a new token immediately, so this is a perfect way to implement the enableFCM() method.
                      All subscribe information assigned to InstanceID, so when you delete it then initiate to unsubscribe all topic. On this way you able to implement disableFCM() method, just turn back off auto-init before you delete it.



                      public class FCMHandler {

                      public void enableFCM(){
                      // Enable FCM via enable Auto-init service which generate new token and receive in FCMService
                      FirebaseMessaging.getInstance().setAutoInitEnabled(true);
                      }

                      public void disableFCM(){
                      // Disable auto init
                      FirebaseMessaging.getInstance().setAutoInitEnabled(false);
                      new Thread(() -> {
                      try {
                      // Remove InstanceID initiate to unsubscribe all topic
                      // TODO: May be a better way to use FirebaseMessaging.getInstance().unsubscribeFromTopic()
                      FirebaseInstanceId.getInstance().deleteInstanceId();
                      } catch (IOException e) {
                      e.printStackTrace();
                      }
                      }).start();
                      }

                      }


                      Step 3. - FCMService implementation - token and message receiving



                      In the last step you need to receive the new token and send direct to your server.
                      Other hand you'll receive your data message and just do it what you want.



                      public class FCMService extends FirebaseMessagingService {

                      @Override
                      public void onNewToken(String token) {
                      super.onNewToken(token);
                      // TODO: send your new token to the server
                      }

                      @Override
                      public void onMessageReceived(RemoteMessage remoteMessage) {
                      super.onMessageReceived(remoteMessage);
                      String from = remoteMessage.getFrom();
                      Map data = remoteMessage.getData();
                      if (data != null) {
                      // TODO: handle your message and data
                      sendMessageNotification(message, messageId);
                      }
                      }

                      private void sendMessageNotification(String msg, long messageId) {
                      // TODO: show notification using NotificationCompat
                      }
                      }


                      I think this solution is clear, simple and transparent. I tested in a production environment and it's works. I hope it was helpful.






                      share|improve this answer





















                      • Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
                        – Hey You
                        Oct 24 at 3:16












                      • Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
                        – János Sicz-Mesziár
                        Nov 11 at 19:54















                      up vote
                      5
                      down vote













                      I did a brief research on what would be the most elegant solution to get back the full control (subscribe and unsubscribe to FCM) as before. Enable and disable the FCM after the user logged in or out.



                      Step 1. - Prevent auto initialization



                      Firebase now handle the InstanceID and everything else which need to generate a registration token. First of all you need to prevent auto initialization. Based on the official set-up documentation you need to add these meta-data values to your AndroidManifest.xml:



                      <?xml version="1.0" encoding="utf-8"?>
                      <application>

                      <!-- FCM: Disable auto-init -->
                      <meta-data android:name="firebase_messaging_auto_init_enabled"
                      android:value="false" />
                      <meta-data android:name="firebase_analytics_collection_enabled"
                      android:value="false" />

                      <!-- FCM: Receive token and messages -->
                      <service android:name=".FCMService">
                      <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                      </intent-filter>
                      </service>

                      </application>


                      Now you disabled the automatic token request process. At the same time you have an option to enable it again at runtime by code.



                      Step 2. - Implement enableFCM() and disableFCM() functions



                      If you enable the auto initialization again then you received a new token immediately, so this is a perfect way to implement the enableFCM() method.
                      All subscribe information assigned to InstanceID, so when you delete it then initiate to unsubscribe all topic. On this way you able to implement disableFCM() method, just turn back off auto-init before you delete it.



                      public class FCMHandler {

                      public void enableFCM(){
                      // Enable FCM via enable Auto-init service which generate new token and receive in FCMService
                      FirebaseMessaging.getInstance().setAutoInitEnabled(true);
                      }

                      public void disableFCM(){
                      // Disable auto init
                      FirebaseMessaging.getInstance().setAutoInitEnabled(false);
                      new Thread(() -> {
                      try {
                      // Remove InstanceID initiate to unsubscribe all topic
                      // TODO: May be a better way to use FirebaseMessaging.getInstance().unsubscribeFromTopic()
                      FirebaseInstanceId.getInstance().deleteInstanceId();
                      } catch (IOException e) {
                      e.printStackTrace();
                      }
                      }).start();
                      }

                      }


                      Step 3. - FCMService implementation - token and message receiving



                      In the last step you need to receive the new token and send direct to your server.
                      Other hand you'll receive your data message and just do it what you want.



                      public class FCMService extends FirebaseMessagingService {

                      @Override
                      public void onNewToken(String token) {
                      super.onNewToken(token);
                      // TODO: send your new token to the server
                      }

                      @Override
                      public void onMessageReceived(RemoteMessage remoteMessage) {
                      super.onMessageReceived(remoteMessage);
                      String from = remoteMessage.getFrom();
                      Map data = remoteMessage.getData();
                      if (data != null) {
                      // TODO: handle your message and data
                      sendMessageNotification(message, messageId);
                      }
                      }

                      private void sendMessageNotification(String msg, long messageId) {
                      // TODO: show notification using NotificationCompat
                      }
                      }


                      I think this solution is clear, simple and transparent. I tested in a production environment and it's works. I hope it was helpful.






                      share|improve this answer





















                      • Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
                        – Hey You
                        Oct 24 at 3:16












                      • Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
                        – János Sicz-Mesziár
                        Nov 11 at 19:54













                      up vote
                      5
                      down vote










                      up vote
                      5
                      down vote









                      I did a brief research on what would be the most elegant solution to get back the full control (subscribe and unsubscribe to FCM) as before. Enable and disable the FCM after the user logged in or out.



                      Step 1. - Prevent auto initialization



                      Firebase now handle the InstanceID and everything else which need to generate a registration token. First of all you need to prevent auto initialization. Based on the official set-up documentation you need to add these meta-data values to your AndroidManifest.xml:



                      <?xml version="1.0" encoding="utf-8"?>
                      <application>

                      <!-- FCM: Disable auto-init -->
                      <meta-data android:name="firebase_messaging_auto_init_enabled"
                      android:value="false" />
                      <meta-data android:name="firebase_analytics_collection_enabled"
                      android:value="false" />

                      <!-- FCM: Receive token and messages -->
                      <service android:name=".FCMService">
                      <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                      </intent-filter>
                      </service>

                      </application>


                      Now you disabled the automatic token request process. At the same time you have an option to enable it again at runtime by code.



                      Step 2. - Implement enableFCM() and disableFCM() functions



                      If you enable the auto initialization again then you received a new token immediately, so this is a perfect way to implement the enableFCM() method.
                      All subscribe information assigned to InstanceID, so when you delete it then initiate to unsubscribe all topic. On this way you able to implement disableFCM() method, just turn back off auto-init before you delete it.



                      public class FCMHandler {

                      public void enableFCM(){
                      // Enable FCM via enable Auto-init service which generate new token and receive in FCMService
                      FirebaseMessaging.getInstance().setAutoInitEnabled(true);
                      }

                      public void disableFCM(){
                      // Disable auto init
                      FirebaseMessaging.getInstance().setAutoInitEnabled(false);
                      new Thread(() -> {
                      try {
                      // Remove InstanceID initiate to unsubscribe all topic
                      // TODO: May be a better way to use FirebaseMessaging.getInstance().unsubscribeFromTopic()
                      FirebaseInstanceId.getInstance().deleteInstanceId();
                      } catch (IOException e) {
                      e.printStackTrace();
                      }
                      }).start();
                      }

                      }


                      Step 3. - FCMService implementation - token and message receiving



                      In the last step you need to receive the new token and send direct to your server.
                      Other hand you'll receive your data message and just do it what you want.



                      public class FCMService extends FirebaseMessagingService {

                      @Override
                      public void onNewToken(String token) {
                      super.onNewToken(token);
                      // TODO: send your new token to the server
                      }

                      @Override
                      public void onMessageReceived(RemoteMessage remoteMessage) {
                      super.onMessageReceived(remoteMessage);
                      String from = remoteMessage.getFrom();
                      Map data = remoteMessage.getData();
                      if (data != null) {
                      // TODO: handle your message and data
                      sendMessageNotification(message, messageId);
                      }
                      }

                      private void sendMessageNotification(String msg, long messageId) {
                      // TODO: show notification using NotificationCompat
                      }
                      }


                      I think this solution is clear, simple and transparent. I tested in a production environment and it's works. I hope it was helpful.






                      share|improve this answer












                      I did a brief research on what would be the most elegant solution to get back the full control (subscribe and unsubscribe to FCM) as before. Enable and disable the FCM after the user logged in or out.



                      Step 1. - Prevent auto initialization



                      Firebase now handle the InstanceID and everything else which need to generate a registration token. First of all you need to prevent auto initialization. Based on the official set-up documentation you need to add these meta-data values to your AndroidManifest.xml:



                      <?xml version="1.0" encoding="utf-8"?>
                      <application>

                      <!-- FCM: Disable auto-init -->
                      <meta-data android:name="firebase_messaging_auto_init_enabled"
                      android:value="false" />
                      <meta-data android:name="firebase_analytics_collection_enabled"
                      android:value="false" />

                      <!-- FCM: Receive token and messages -->
                      <service android:name=".FCMService">
                      <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                      </intent-filter>
                      </service>

                      </application>


                      Now you disabled the automatic token request process. At the same time you have an option to enable it again at runtime by code.



                      Step 2. - Implement enableFCM() and disableFCM() functions



                      If you enable the auto initialization again then you received a new token immediately, so this is a perfect way to implement the enableFCM() method.
                      All subscribe information assigned to InstanceID, so when you delete it then initiate to unsubscribe all topic. On this way you able to implement disableFCM() method, just turn back off auto-init before you delete it.



                      public class FCMHandler {

                      public void enableFCM(){
                      // Enable FCM via enable Auto-init service which generate new token and receive in FCMService
                      FirebaseMessaging.getInstance().setAutoInitEnabled(true);
                      }

                      public void disableFCM(){
                      // Disable auto init
                      FirebaseMessaging.getInstance().setAutoInitEnabled(false);
                      new Thread(() -> {
                      try {
                      // Remove InstanceID initiate to unsubscribe all topic
                      // TODO: May be a better way to use FirebaseMessaging.getInstance().unsubscribeFromTopic()
                      FirebaseInstanceId.getInstance().deleteInstanceId();
                      } catch (IOException e) {
                      e.printStackTrace();
                      }
                      }).start();
                      }

                      }


                      Step 3. - FCMService implementation - token and message receiving



                      In the last step you need to receive the new token and send direct to your server.
                      Other hand you'll receive your data message and just do it what you want.



                      public class FCMService extends FirebaseMessagingService {

                      @Override
                      public void onNewToken(String token) {
                      super.onNewToken(token);
                      // TODO: send your new token to the server
                      }

                      @Override
                      public void onMessageReceived(RemoteMessage remoteMessage) {
                      super.onMessageReceived(remoteMessage);
                      String from = remoteMessage.getFrom();
                      Map data = remoteMessage.getData();
                      if (data != null) {
                      // TODO: handle your message and data
                      sendMessageNotification(message, messageId);
                      }
                      }

                      private void sendMessageNotification(String msg, long messageId) {
                      // TODO: show notification using NotificationCompat
                      }
                      }


                      I think this solution is clear, simple and transparent. I tested in a production environment and it's works. I hope it was helpful.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 9 at 22:02









                      János Sicz-Mesziár

                      12112




                      12112












                      • Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
                        – Hey You
                        Oct 24 at 3:16












                      • Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
                        – János Sicz-Mesziár
                        Nov 11 at 19:54


















                      • Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
                        – Hey You
                        Oct 24 at 3:16












                      • Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
                        – János Sicz-Mesziár
                        Nov 11 at 19:54
















                      Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
                      – Hey You
                      Oct 24 at 3:16






                      Hello Janos , if i don't enable the auto init by calling "FirebaseMessaging.getInstance().setAutoInitEnabled(true);" what is the impact ? Will app get "onNewToken" callback or not ?
                      – Hey You
                      Oct 24 at 3:16














                      Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
                      – János Sicz-Mesziár
                      Nov 11 at 19:54




                      Oh.. sorry my late answer. Yes, after you enable it again, you get a new token in FCMService via call onNewToken().
                      – János Sicz-Mesziár
                      Nov 11 at 19:54










                      up vote
                      2
                      down vote













                      I know I am late for the party. deleteInstanceId() should be called from the background thread since it's a blocking call. Just check the method deleteInstanceId() in FirebaseInstanceId() class.



                      @WorkerThread
                      public void deleteInstanceId() throws IOException {
                      if (Looper.getMainLooper() == Looper.myLooper()) {
                      throw new IOException("MAIN_THREAD");
                      } else {
                      String var1 = zzh();
                      this.zza(this.zzal.deleteInstanceId(var1));
                      this.zzl();
                      }
                      }


                      You can start an IntentService to delete the instance id and the data associated with it.






                      share|improve this answer





















                      • This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
                        – Michał K
                        Jul 26 at 6:21















                      up vote
                      2
                      down vote













                      I know I am late for the party. deleteInstanceId() should be called from the background thread since it's a blocking call. Just check the method deleteInstanceId() in FirebaseInstanceId() class.



                      @WorkerThread
                      public void deleteInstanceId() throws IOException {
                      if (Looper.getMainLooper() == Looper.myLooper()) {
                      throw new IOException("MAIN_THREAD");
                      } else {
                      String var1 = zzh();
                      this.zza(this.zzal.deleteInstanceId(var1));
                      this.zzl();
                      }
                      }


                      You can start an IntentService to delete the instance id and the data associated with it.






                      share|improve this answer





















                      • This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
                        – Michał K
                        Jul 26 at 6:21













                      up vote
                      2
                      down vote










                      up vote
                      2
                      down vote









                      I know I am late for the party. deleteInstanceId() should be called from the background thread since it's a blocking call. Just check the method deleteInstanceId() in FirebaseInstanceId() class.



                      @WorkerThread
                      public void deleteInstanceId() throws IOException {
                      if (Looper.getMainLooper() == Looper.myLooper()) {
                      throw new IOException("MAIN_THREAD");
                      } else {
                      String var1 = zzh();
                      this.zza(this.zzal.deleteInstanceId(var1));
                      this.zzl();
                      }
                      }


                      You can start an IntentService to delete the instance id and the data associated with it.






                      share|improve this answer












                      I know I am late for the party. deleteInstanceId() should be called from the background thread since it's a blocking call. Just check the method deleteInstanceId() in FirebaseInstanceId() class.



                      @WorkerThread
                      public void deleteInstanceId() throws IOException {
                      if (Looper.getMainLooper() == Looper.myLooper()) {
                      throw new IOException("MAIN_THREAD");
                      } else {
                      String var1 = zzh();
                      this.zza(this.zzal.deleteInstanceId(var1));
                      this.zzl();
                      }
                      }


                      You can start an IntentService to delete the instance id and the data associated with it.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 26 at 6:18









                      Sarweshkumar C R

                      1891312




                      1891312












                      • This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
                        – Michał K
                        Jul 26 at 6:21


















                      • This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
                        – Michał K
                        Jul 26 at 6:21
















                      This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
                      – Michał K
                      Jul 26 at 6:21




                      This is true but irrelevant here (also other answers wrapped it in asynctask which is basically the same)
                      – Michał K
                      Jul 26 at 6:21










                      up vote
                      0
                      down vote













                      Since the getToken() is deprecated, use getInstanceId() to regenerate new token instead. It has same effect.



                      public static void resetInstanceId() {
                      new Thread(new Runnable() {
                      @Override
                      public void run() {
                      try {
                      FirebaseInstanceId.getInstance().deleteInstanceId();
                      FirebaseInstanceId.getInstance().getInstanceId();
                      Helper.log(TAG, "InstanceId removed and regenerated.");
                      } catch (IOException e) {
                      e.printStackTrace();
                      }
                      }
                      }).start();
                      }





                      share|improve this answer



























                        up vote
                        0
                        down vote













                        Since the getToken() is deprecated, use getInstanceId() to regenerate new token instead. It has same effect.



                        public static void resetInstanceId() {
                        new Thread(new Runnable() {
                        @Override
                        public void run() {
                        try {
                        FirebaseInstanceId.getInstance().deleteInstanceId();
                        FirebaseInstanceId.getInstance().getInstanceId();
                        Helper.log(TAG, "InstanceId removed and regenerated.");
                        } catch (IOException e) {
                        e.printStackTrace();
                        }
                        }
                        }).start();
                        }





                        share|improve this answer

























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          Since the getToken() is deprecated, use getInstanceId() to regenerate new token instead. It has same effect.



                          public static void resetInstanceId() {
                          new Thread(new Runnable() {
                          @Override
                          public void run() {
                          try {
                          FirebaseInstanceId.getInstance().deleteInstanceId();
                          FirebaseInstanceId.getInstance().getInstanceId();
                          Helper.log(TAG, "InstanceId removed and regenerated.");
                          } catch (IOException e) {
                          e.printStackTrace();
                          }
                          }
                          }).start();
                          }





                          share|improve this answer














                          Since the getToken() is deprecated, use getInstanceId() to regenerate new token instead. It has same effect.



                          public static void resetInstanceId() {
                          new Thread(new Runnable() {
                          @Override
                          public void run() {
                          try {
                          FirebaseInstanceId.getInstance().deleteInstanceId();
                          FirebaseInstanceId.getInstance().getInstanceId();
                          Helper.log(TAG, "InstanceId removed and regenerated.");
                          } catch (IOException e) {
                          e.printStackTrace();
                          }
                          }
                          }).start();
                          }






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 20 at 14:53









                          morten.c

                          2,63522838




                          2,63522838










                          answered Nov 20 at 13:11









                          Reedy Creeker

                          394




                          394






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43193215%2ffirebase-cloud-messaging-handling-logout%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              To store a contact into the json file from server.js file using a class in NodeJS

                              Redirect URL with Chrome Remote Debugging Android Devices

                              Dieringhausen