我正在构建一个应用程序,登录的用户可以通过按下按钮邀请另一个用户,这样被邀请的用户就会收到推送通知。我的想法是,如果我可以将每个用户的令牌保存在数据库中;"邀请按钮";它会在数据库中发现users令牌,然后我会以某种方式使用它向该用户发送通知。我不知道是否有更好的方法,但我没有找到其他方法,所以这是我目前的计划。
现在我遇到了一些关于如何将令牌保存到数据库的问题。我想在用户创建帐户或令牌更改时将其保存到数据库中。
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
因此,我真正想问的是如何获得用户的当前令牌?
Firebase云消息令牌是设备唯一的,而不是用户。它对Firebase Auth用户一无所知,对FCM设备令牌也一无所知。
您需要存储用户到其设备令牌的映射。由于一个用户可以使用多个设备,因此您的数据结构应该允许每个用户使用多个令牌。然后,您的后端代码应该查询这些令牌,并将消息发送给其中的每一个令牌(如果这是您的用户想要的(。
您可以使用此代码获取当前用户id。
FirebaseAuth.getInstance().getCurrentUser().getUid();
可以从FirebaseMessagingService类的onNewToken中获取新令牌。
@Override
public void onNewToken(String token) {
super.onNewToken(token);
}