Check if user is authenticated for the first time in Firebase Google Authentication in Android
To check if it's the first time user logs in, simply call the AdditionalUserInfo.isNewUser()
method in the OnCompleteListener.onComplete
callback.
Example code below, be sure to check for null.
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNew = task.getResult().getAdditionalUserInfo().isNewUser();
Log.d("MyTAG", "onComplete: " + (isNew ? "new user" : "old user"));
}
}
};
Check the docs for more reference AdditionalUserInfo
From the Firebase-ui docs, you can check the last sign-in timestamp against the created-at timestamp like this:
FirebaseUserMetadata metadata = auth.getCurrentUser().getMetadata();
if (metadata.getCreationTimestamp() == metadata.getLastSignInTimestamp()) {
// The user is new, show them a fancy intro screen!
} else {
// This is an existing user, show them a welcome back screen.
}
According to the new version of Firebase auth (16.0.1) The AuthResult class has a member function which results true or false (is the user is new). Assuming "credential" is defined in the scope(it is the google credential ). An example is shown below: `
private FirebaseAuth mAuth;
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mAuth = FirebaseAuth.getInstance();
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
GoogleSignInAccount acct = task.getResult(ApiException.class);
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, "linkWithCredential:success");
boolean newuser = task.getResult().getAdditionalUserInfo().isNewUser();
if(newuser){
//Do Stuffs for new user
}else{
//Continue with Sign up
}
} else {
Toast.makeText(MyClass.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
});
Thanks to firebase:)