arieliito
arieliito

Reputation: 197

FirebaseInstanceId.getInstance().getToken() deprecated how to save token in DB

i wan't to know how to implement the new FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener into my own code so i can retrieve the token and save it into the database to use FCM and identify every user.

Actually i have the following code:

if (task.isSuccessful()) {
final String deviceToken = FirebaseInstanceId.getInstance().getToken();

Map<String, Object> createUser = new HashMap<>();
                                createUser.put("name", name);
                                createUser.put("email", email);
                                createUser.put("device_token", deviceToken);

Ref.child("Users").child(task.getResult().getUser().getUid()).updateChildren(createUser);

according to actual firebase instructions, i should modify as follows:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>(){
    @Override
    public void onSuccess(InstanceIdResult instanceIdResult) {
    String deviceToken = instanceIdResult.getToken();
    Log.e("newToken", deviceToken);
    }
});

Map<String, Object> createUser = new HashMap<>();
                                createUser.put("name", name);
                                createUser.put("email", email);
                                createUser.put("device_token", deviceToken);

Ref.child("Users").child(task.getResult().getUser().getUid()).updateChildren(createUser);

but i don't know how to get the deviceToken string out of the method, should i save it to shared preferences and then retrieve it from there?

Because if i want to declare "deviceToken" as global, it won't be allowed as it needs to be declared final.

Thanks!

Upvotes: 5

Views: 5754

Answers (2)

yogibali
yogibali

Reputation: 21

its deprecated, in gradle update implementation 'com.google.firebase:firebase-messaging:21.0.0' use code below:

FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
            @Override
            public void onComplete(@NonNull Task<String> task) {
                if (!task.isSuccessful()) {
                    return;
                }
                // Get new FCM registration token
                String token= task.getResult();
            }
        });

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

You should save the token from within the onSuccess callback of the getInstanceId() call:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>(){
  @Override
  public void onSuccess(InstanceIdResult instanceIdResult) {
    String deviceToken = instanceIdResult.getToken();
    Log.e("newToken", deviceToken);

    ... save the token to your database here
  }
});

Upvotes: 1

Related Questions