android 如何获取当前用户的Firebase令牌

wbgh16ku  于 2023-02-20  发布在  Android
关注(0)|答案(3)|浏览(230)

我正在开发一个应用程序,登录用户可以通过按下按钮邀请另一个用户,这样被邀请的用户就会收到一个推送通知。我的想法是,如果我可以在数据库中保存每个用户的令牌,然后,当用户按下"邀请按钮"时,它会在数据库中找到该用户的令牌,之后我会以某种方式使用它向该用户发送通知。我不知道是否有更好的方法,但我没有找到任何其他的东西,所以这是我目前的计划。
现在我遇到了一些关于如何将令牌保存到数据库的问题。我想在用户创建帐户或令牌更改时将其保存到数据库。

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();

    }
}

我想要做的是将令牌保存在数据库的用户中,同时保存其他变量,如用户名、年龄等。
我本来希望会有这样的东西来获得令牌,但似乎不是这样:

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

因此,我真正要问的是如何为用户获取当前令牌?

4jb9z9bj

4jb9z9bj1#

Firebase云消息令牌对设备是唯一的,而对用户不是唯一的。它对Firebase Auth用户一无所知,而Firebase Auth对FCM设备令牌也一无所知。
你需要存储用户到他们的设备令牌的Map。由于一个用户可以使用多个设备,你的数据结构应该允许每个用户有多个令牌。然后,你的后端代码应该查询这些令牌,并向每个令牌发送消息(如果这是你的用户想要的)。

yzxexxkh

yzxexxkh2#

您可以使用此代码获取当前用户id。
FirebaseAuth.getInstance().getCurrentUser().getUid();

3xiyfsfu

3xiyfsfu3#

可以从FirebaseMessagingService类的onNewToken获取新令牌。

@Override
        public void onNewToken(String token) {
            super.onNewToken(token);
        }

相关问题