Skip to content
Advertisement

How to get Firebase token of current user

I’m buildning an app where a logged in user can invite another user through pressing a button, so then the invited user will get a push notification. My idea is that if I can save the token for each user in the database, then when a user presses the “invite button” it will find that users token in the database and after that I will somehow use it to send a notification to that user. I don’t know if there is a better way of doing it, but I didn’t find anything else on it so that is my current plan.

Now I have run into some issues regarding how to save the token to the database. I want to do save it to the database whenever a user creates an account or the token changes.

public class RegisterActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;

    String username;
    String password;
    String age;
    String email;
    
    DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference mRootPlayerBaseRef = mRootRef.child("Players");

    private static final String TAG = "EmailPassword";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // [START initialize_auth]
        // Initialize Firebase Authentication
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]
    }


    private void updateUI() {
        Intent mainIntent = new Intent(RegisterActivity.this, LoginActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mainIntent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void checkValues(View view) {
        final EditText userEdit = (EditText) findViewById(R.id.username_field);
        username = userEdit.getText().toString();
        final EditText emailEdit = (EditText) findViewById(R.id.email_field);
        email = emailEdit.getText().toString();
        final EditText passwordEdit = (EditText) findViewById(R.id.password_field);
        password = passwordEdit.getText().toString();
        final EditText ageEdit = (EditText) findViewById(R.id.age_field);
        age = ageEdit.getText().toString();


        if (username.equals("") || email.equals("") || password.equals("") || age.equals("")){
            Toast.makeText(RegisterActivity.this, "Please fill in all information", Toast.LENGTH_LONG).show();
            return;}

        if (username.length() < 4){
            Toast.makeText(RegisterActivity.this, "Username has to be at least 4 characters", Toast.LENGTH_LONG).show();
            return;
        }

        if (Integer.parseInt(age) < 5 || Integer.parseInt(age) > 120){
            Toast.makeText(RegisterActivity.this, "Enter a valid age", Toast.LENGTH_LONG).show();
            return;
        }

        //last thing to check is if username already exists
        checkUsedUsername(username);

    }

    public void login(View view) {
        Intent mainIntent = new Intent(RegisterActivity.this, LoginActivity.class);
        startActivity(mainIntent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void checkUsedUsername(final String username){
        mRootPlayerBaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                //check if username exist otherwise create account
                for (DataSnapshot data: dataSnapshot.getChildren()) {
                    if (username.equals(data.child("username").getValue())){
                        Toast.makeText(RegisterActivity.this, "Username already taken", Toast.LENGTH_LONG).show();
                        return;}
                }
                createAccount();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(RegisterActivity.this, "Error", Toast.LENGTH_SHORT).show();
                Toast.makeText(RegisterActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void createAccount(){
        // [START create_user_with_email], built in function which checks if user can be created and insert it into auth database
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        //if this was successful the user will now be in the database
                        if (task.isSuccessful()) {
                            //fetch the user
                            FirebaseUser user = mAuth.getCurrentUser();

                            //this set the created users getDisplayName() = username
                            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                                    .setDisplayName(username).build();
                            assert user != null;
                            user.updateProfile(profileUpdates);

                            //Here I would like to get the token so I can save it when a user is created

                            //get unique user id
                            String userID = user.getUid();
                            //create the user that will be inserted into the database
                            Player newPlayer = new Player(username, age, email);
                            //adding child(userID) will make we donĀ“t replace previous user and actually insert new user, it becomes the key
                            mRootPlayerBaseRef.child(userID).setValue(newPlayer);

                            Toast.makeText(RegisterActivity.this, "Account was created successfully", Toast.LENGTH_LONG).show();
                            updateUI();
                        } else {
                            try
                            {
                                throw Objects.requireNonNull(task.getException());
                            }
                            // if user enters wrong email.
                            catch (FirebaseAuthWeakPasswordException weakPassword)
                            {
                                Log.d(TAG, "onComplete: weak_password");
                                Toast.makeText(RegisterActivity.this, "Password to weak", Toast.LENGTH_LONG).show();
                            }
                            // if user enters wrong password.
                            catch (FirebaseAuthInvalidCredentialsException malformedEmail)
                            {
                                Log.d(TAG, "onComplete: malformed_email");
                                Toast.makeText(RegisterActivity.this, "Wrong email", Toast.LENGTH_LONG).show();
                            }
                            catch (FirebaseAuthUserCollisionException existEmail)
                            {
                                Log.d(TAG, "onComplete: exist_email");
                                Toast.makeText(RegisterActivity.this, "Email already exists", Toast.LENGTH_LONG).show();
                            }
                            catch (Exception e)
                            {
                                Toast.makeText(RegisterActivity.this, "Error", Toast.LENGTH_SHORT).show();
                                Toast.makeText(RegisterActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });
        // [END create_user_with_email]
    }
}
public class MessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.d("NEW_TOKEN",s); //here we get the token so we can communicate with the database
    }

    //does not work as "Method does not override method from its superclass"
    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();

    }
}

What I want to do is to save the token in the user in the database together with the other variables such as username, age, etc.

I was hoping there would be something like this to get the token, but it doesn’t seem that way:

FirebaseAuth.getInstance().getCurrentUser().getIdToken(true) //this does not work

So what I’m really asking is how do I get the current token for the user?

Advertisement

Answer

Firebase Cloud Messaging tokens are unique to the device, not the user. It doesn’t know anything about Firebase Auth users, and Firebase Auth doesn’t know anything about FCM device tokens.

You will need to store a mapping of users to their device tokens. Since a user could be using multiple devices, your data structure should allow for multiple tokens for each user. Then, your backend code should query for those tokens and send the message to each one of them (if that’s what your users want).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement