Firebase Cloud Messaging notification from Java instead of Firebase Console

前端 未结 7 1754
野趣味
野趣味 2020-12-12 16:21

I am new to Firebase and I am running into errors such as mismatch sender id and Authentication Error with HTTP status 401 when my Java application tries to send a notificat

相关标签:
7条回答
  • 2020-12-12 17:23

    I had the exacly same problem, and even used your code as a test to check if there was something wrong with mine. It turns out that both of our codes were right. The problem is exacly as described on Firebase docs:

    "Mismatched Sender 200 + error:MismatchSenderId A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work."

    Problem is, that´s not that clear (at least wasn´t for me). So here's what you need: On your Android application, you'll need to receive the Firebase key for the device . It is not the same you used to have for the Google Cloud Message, and hence there´s the problem.

    Just create this class on your Android project:

    public class NotificacaoRegistro extends FirebaseInstanceIdService { static private String TAG = "NOTIFICACAOREGISTRO";

    public NotificacaoRegistro(){
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
    }
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        // TODO: Implement this method to send any registration to your app's servers.
    
    }
    

    }

    Don't forget to make the necessary changes on your AndroidManifest

      <service
                android:name=".notificacoes.NotificacaoRegistro">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
                </intent-filter>
      </service>
    

    If you just need the code (for debugging, for example) you can just call on your MainActivity, in your OnCreate method

    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    But it´s better, ofc if you take care of that properly.

    That way you'll get the correct key for that device. Then on your Java application code

       Result result = sender.send(message,
                <PUT THE VALUE OF THE REFRESHED TOKEN HERE>,
                        1);
    

    and you are all set :)

    Hope this helps, and sorry about the long delay :)

    cheers

    0 讨论(0)
提交回复
热议问题