如何检测用户是否首次在Firebase中

Op.*_*mal 5 android firebase firebase-authentication

我需要检查用户是否是首次登录,并使用true的其他属性(积分,会员资格等)来初始化其帐户。

可能用户更改了设备并希望再次登录另一台设备。

我正在使用Google登录方法。我尝试过这样的事情。

if(FirebaseAuth.getInstance().getCurrentUser() != null){
                           Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
                       }
Run Code Online (Sandbox Code Playgroud)

我使用新帐户登录,因此是第一次使用此应用程序登录,但无论如何都会显示“ 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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

更新

我收到错误消息:“;” 预期这条线

mAuth.signInWithCredential(credential)
Run Code Online (Sandbox Code Playgroud)

这是怎么了?更换。

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!");
                }
            }

        });

    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*amo 8

如何检测用户是否第一次使用 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!");
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

更多信息请查看官方文档

编辑:为了使其工作,您需要添加一个完整的侦听器。请看下面的代码:

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!");
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

或者更简单:

mAuth.signInWithCredential(credential).addOnCompleteListener(this, completeListener);
Run Code Online (Sandbox Code Playgroud)

其中,completeListener对象是最先定义的对象。


归档时间:

查看次数:

1137 次

最近记录:

7 年,2 月 前