我需要检查用户是否是首次登录,如果是,则使用其他属性(积分,会员资格等)初始化其帐户。
可以让用户更改其设备并希望再次在另一台设备上登录。
我正在使用Google登录方法。我尝试过这样的事情。
if(FirebaseAuth.getInstance().getCurrentUser() != null){
Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
}
我使用新帐户登录,所以是第一次使用此应用程序登录,但无论如何仍显示“ Welcome again xyz”消息。
如何检测以前用户是否存在于数据库中?
完整代码
package com.mertg.testsignin;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.FirebaseDatabase;
public class Anamain extends AppCompatActivity {
private String TAG = "Anamain";
private SignInButton signIn;
GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 1;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anamain);
signIn = (SignInButton)findViewById(R.id.googleBtn);
mAuth = FirebaseAuth.getInstance();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("TAG", "signInWithCredential:success" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
/* if (!task.isSuccessful()){
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}*/
if(FirebaseAuth.getInstance().getCurrentUser() != null){
Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
}
else {
//Log.w("TAG", "signInWithCredential:failure", task.getException());
// Toast.makeText(Anamain.this, "Basaramadim", Toast.LENGTH_SHORT).show();
//updateUI(null);
Toast.makeText(Anamain.this, "Register Successful", Toast.LENGTH_SHORT).show();
FirebaseUser user = mAuth.getCurrentUser();
//updateUI(user);
}
}
});
}
private void updateUI(FirebaseUser user) {
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if(acct != null) {
String personName = acct.getDisplayName();
Toast.makeText(this, "Sen Girdin" + personName, Toast.LENGTH_SHORT).show();
}
}
}
更新
我得到错误:';'该行应有
mAuth.signInWithCredential(credential)
这是替换方式
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("TAG", "signInWithCredential:success" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d(TAG, "Is New User!");
} else {
Log.d(TAG, "Is Old User!");
}
}
});
}
答案 0 :(得分:2)
如何检测用户是否是首次使用Firebase?
如果您要检查用户是否首次登录,则检查用户是否是新用户也是一样。因此,要解决此问题,您只需调用AdditionalUserInfo的isNewUser()方法:
返回用户是新用户还是现有用户
在OnCompleteListener.onComplete
回调中,如下所示:
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d("TAG", "Is New User!");
} else {
Log.d("TAG", "Is Old User!");
}
}
}
};
有关更多信息,请参见official documentation。
编辑:为了使其正常工作,您需要添加完整的侦听器。请参见下面的代码:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d(TAG, "Is New User!");
} else {
Log.d(TAG, "Is Old User!");
}
}
});
或更简单:
mAuth.signInWithCredential(credential).addOnCompleteListener(this, completeListener);
其中completeListener
对象是首先定义的对象。
答案 1 :(得分:0)
您可以在数据库中拥有user node
,可以在其中添加key
作为uuid
,并将值添加为其唯一的uuid
,如果您的用户是首次访问,您将无法在用户节点上获得uuid
,因此您可以在数据库中初始化用户时在其中添加uuid
答案 2 :(得分:0)
在数据库中创建isFirstTime = false
类型的标志。首次安装该应用程序时,将其设置为true
。
答案 3 :(得分:0)
仅分享我在新用户问题上的先前实现。
我在项目中使用了 Firebase Cloud Firestore ,所以我创建了另一个表来存储用户的基本信息。
首先,我创建一个名为createUser()
的方法,但是基本上,它通过查询Firebase Cloud Firestore数据库来检查它是否是首次使用。如果不存在,请为该用户创建一个文档,然后您可以对他们执行操作,在下面的代码中查找//you can add some action here
。
下面是我上一个项目的实际代码,其中包括一个基于角色的管理来控制用户访问权限(如果您感兴趣,请参考)。
public void createUser(){
docRef = mFirestore.collection("users").document(auth.getCurrentUser().getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
//if the user is already in the database, check the user role
if (document != null && document.exists()) {
User user = document.toObject(User.class);
if(user.getRoles().get("admin")==true){
Log.d(TAG, "Admin: true");
btn_admin.setVisibility(View.VISIBLE);
}
else{
Log.d(TAG, "Admin: false");
btn_admin.setVisibility(View.GONE);
}
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
//check whether it's a new user
//if yes, create a new document containing the user details thru my User model
Log.d(TAG, "No such document");
btn_admin.setVisibility(View.GONE);
Map<String, Boolean> roles = new HashMap<>();
roles.put("editor", false);
roles.put("viewer", false);
roles.put("admin", false);
User user = new User(auth.getCurrentUser().getDisplayName(), auth.getCurrentUser().getUid(),auth.getCurrentUser().getEmail(), roles);
//you can add some action here
mFirestore.collection("users").document(auth.getCurrentUser().getUid())
.set(user, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
//Log.d(TAG, "Created credential");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}