如何检测用户是否首次在Firebase中 [英] How can I detect if user first time in Firebase

查看:46
本文介绍了如何检测用户是否首次在Firebase中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查用户是否是第一次登录,如果是,则使用其他属性(积分,会员资格等)来初始化其帐户.

I need to check if the user is signing in for the first time, and initialize their account with extra properties (points, membership, etc) if true.

可以让用户更改其设备并希望再次在另一台设备上登录.

May user change his device and wants login again on another device.

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

I'm using google sign-in method. I tried something like this.

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

我使用新帐户登录,因此是第一次使用此应用程序登录,但无论如何都会显示"Welcome again xyz"消息.

I sign-in with new account, so first time in this app, but it's show "Welcome again xyz" message anyway.

如何检测以前用户是否存在于数据库中?

How can I detect if user exist on database before?

完整代码

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

}

更新

我得到错误:';'该行应有

I get error: ';' expected for this line

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

        });

    }

推荐答案

如何检测用户是否是首次使用Firebase?

How can I detect if user first time in Firebase?

如果您要检查用户是否首次登录,则检查用户是否是新用户也是一样.因此,要解决此问题,您只需调用AdditionalUserInfo的 isNewUser()方法:

If you want to check if the user logs in for the first time, it's the same thing if you check if a user is new. So to solve this, you can simply call AdditionalUserInfo's isNewUser() method:

返回用户是新用户还是现有用户

Returns whether the user is new or existing

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

有关更多信息,请参见官方文档.

For more informations, please see the official documentation.

编辑:为了使其正常工作,您需要添加完整的侦听器.请参见下面的代码:

In order to make it work, you need to add a complete listener. Please see the code below:

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对象是首先定义的对象.

In which, the completeListener object is the object that was defined first.

这篇关于如何检测用户是否首次在Firebase中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆