简体   繁体   中英

How can I store FireBase Cloud Messaging tokens in firebase database in Android?

I am building a chat application and using FCM services.

When the user signs up on the app I am able to get the token by

 String token1;       FirebaseMessaging.getInstance().getToken()
                                    .addOnCompleteListener(new OnCompleteListener<String>() {
                                        @Override
                                        public void onComplete(@NonNull Task<String> task) {
                                            if (!task.isSuccessful()) {
                                                Log.w("TTTTTTTTTTTT", "Fetching FCM registration token failed", task.getException());
                                                return;
                                            }

                                            // Get new FCM registration token
                                            token1 = task.getResult();  //this is the token

                                            // Log 
                                            Log.d("TTTTTTTTTTTT", token1);

                                        }
                                    });

Now, after getting the token I want to store it in Firebase Database along with the associated user.

So the User would have a email, a password, a city and a token .

signUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String em = email.getText().toString();
                String pass = password.getText().toString();
                final String na = name.getText().toString();
                final String ci = city.getText().toString();
                if (em.equals("") || pass.equals("") || na.equals("") || ci.equals("")) {
                    name.setError("Enter your name");
                    password.setError("Enter your password");
                    city.setError("Enter your city");
                    email.setError("Enter your email");
                    Toast.makeText(ActivitySignup.this, "Please fill all the Fields", Toast.LENGTH_SHORT).show();
                } else {
                    progressBar.setVisibility(View.VISIBLE);

                    FirebaseAuth.getInstance().createUserWithEmailAndPassword(em, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                progressBar.setVisibility(View.GONE);




FirebaseDatabase.getInstance().getReference().child("USERS").
child(task.getResult().getUser().getUid()).
setValue(new UserModel(em, na, ci,token1 ));  //Creating a new user and storing name ,email, city and token in database


startActivity(new Intent(ActivitySignup.this, YearChooseActivity.class).putExtra("activity_name", "ActivitySignUp")
.putExtra("timesVisited", timesVisited));

                                Toast.makeText(ActivitySignup.this, "Successfully Register User \n" + em, Toast.LENGTH_SHORT).show();
                            } else {
                                progressBar.setVisibility(View.GONE);

                                Toast.makeText(ActivitySignup.this, Objects.requireNonNull(Objects.requireNonNull(task.getException()).getMessage()).toString(), Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            }

        });

FirebaseDatabase.getInstance().getReference().child("USERS").child(task.getResult().getUser().getUid()).setValue(new UserModel(email, name, city, token1 )); //Creating a new user and storing name,email,

The problem is that the token does not gets stored in Firebase. When I pass a random String as the token parameter lets say I pass " Kobe will be remembered" as the argument

FirebaseDatabase.getInstance().getReference().child("USERS").child(task.getResult().getUser().getUid()).setValue(new UserModel(email, name, city," Kobe will be remembered" )); //Creating a new user and storing name,email,

Then it gets stored in the database pretty well.

When I sign up with a test user let's say name=a, email = a@gmail.com, city = a then in the realtime database the token is not saved. This is how the realtime database looks.

"aBnS2fuXo2gmvcxzqy3z3mgFpiv2" : {
      "city" : "a",
      "email" : "a@gmail.com",
      "name" : "a"
    }

But when I hardcode the token value to a random string lets say "Arnold" by using FirebaseDatabase.getInstance().getReference().child("USERS").child(task.getResult().getUser().getUid()).setValue(new UserModel(email, name, city,"Arnold" ));

then the database looks like

"aBnS2fuXo2gmvcxzqy3z3mgFpiv2" : {
      "city" : "a",
      "email" : "a@gmail.com",
      "name" : "a"
      "userToken" : "Arnold",

    }

For notification I need the token for the opposing party, hence how do I store the token of all users in firebase along with their other credentials?

you definitely don't store them in the same location it's not good security practice. also, the user may sign out or change their phones you don't want to send the notifications to the old device.

save the FCM token under the user information or a subcollection. then if you want to message them using that token you just use their UID to get their token and send them a message. You can securely do that using cloud functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM