java - 如何获取当前用户的 Firebase token

标签 java android firebase firebase-authentication firebase-cloud-messaging

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

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

    }
}
我想要做的是将用户中的 token 与其他变量(如用户名、年龄等)一起保存在数据库中。
我希望有这样的东西来获得 token ,但似乎不是这样:
FirebaseAuth.getInstance().getCurrentUser().getIdToken(true) //this does not work
所以我真正要问的是如何为用户获取当前 token ?

最佳答案

Firebase 云消息传递 token 是 独有的。设备 ,而不是 用户 .它对 Firebase Auth 用户一无所知,Firebase Auth 对 FCM 设备 token 一无所知。
您将需要存储用户与其设备 token 的映射。由于用户可能使用多个设备,因此您的数据结构应该允许每个用户使用多个 token 。然后,您的后端代码应该查询这些 token 并将消息发送给每个 token (如果这是您的用户想要的)。

关于java - 如何获取当前用户的 Firebase token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62799685/

相关文章:

android - 从 Canvas 上删除,最后一个 canvas.drawPath()

java - 为数组长度设置 ArrayIndexOutOfBound 异常

java - 使用 Jetty 8 时无法访问 Neo4j Web 界面

java - 为什么我必须将 TextField 声明为 public,而不是 Label

ios - 如何在 iOS swift 中自动登录用户?

ios - Firebase 规则访问特定 child 的值(value)

firebase - 使用 Geofire + Firebase 过滤结果

java - 从 JList 中删除元素不起作用

android - 在一个Google Play开发者帐户中使用不同的软件包名称

android - 清除所有剪贴板条目