M4rkus123
M4rkus123

Reputation: 5

Unable to find FCM token

I am trying to implement notifications and can send a notification using the firebase console to all devices of the app, however I am having problem trying to retrieve the token of a device so i can send the notification to one particular device. I have a service that extends FirebaseMessagingService and includes the method onNewtoken seen below. I have added this service to my manifest and tried running the app but still unable to find the token. Is there something im doing wrong?

  @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.d("NEW_TOKEN",s);
    }

Upvotes: 0

Views: 151

Answers (2)

Arunachalam k
Arunachalam k

Reputation: 744

OnNewtoken will trigger only by following below scenarios

  • The app deletes Instance ID
  • The app is restored on a new device
  • The user uninstalls/reinstalls the app The user clears app data.

you can get user token by below code as well

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
    @Override
    public void onSuccess(InstanceIdResult instanceIdResult) {
        String token = instanceIdResult.getToken();
        // send it to server
    }
});

Upvotes: 1

Fahid Mahmood
Fahid Mahmood

Reputation: 43

You can get token forcefully like this u can call this code from onCreate() as sometimes when app has already generated to token it does not call onNewToken

FirebaseInstanceId.getInstance().getInstanceId()
    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
    @Override
    public void onComplete(@NonNull Task<InstanceIdResult> task) {
        if (!task.isSuccessful()) {
            KLog.w("getInstanceId failed", task.getException());
            return;
        }
        // Get new Instance ID token
        if (task.getResult() != null) {
            String token = task.getResult().getToken();
        }
    }
});

Upvotes: 0

Related Questions