执行命令firebase身份验证

时间:2017-04-11 03:01:37

标签: android authentication firebase firebase-authentication

我正在尝试使用facebook sdk和android中的“用户/密码”选项使用firebase身份验证登录。我需要知道在启动MainActivity之前用户使用了哪种身份验证。

几天前代码工作正常,但我不得不删除firebase项目。今天我配置了firebase / facebook sdk,它可以工作。但是现在代码的执行顺序是不同的(我知道这很奇怪)。

之前,onComplete方法(当我验证任务是否成功时)首先执行,然后执行onAuthStateChanged。但现在首先执行第一个onAuthStateChanged方法,启动另一个活动,然后验证任务是否成功。我在调试模式下看到了这种行为。

这是代码示例,我很感激提前获得任何帮助

fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            //Inicio de sesion con facebook exitoso
            handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            //Inicio de sesion con facebook cancelado
            Toast.makeText(getApplicationContext(),R.string.cancel_fb_log,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            //Inicio de sesion con facebook erroneo
            Toast.makeText(getApplicationContext(),R.string.error_fb_log,Toast.LENGTH_SHORT).show();
        }
    });



private void handleFacebookAccessToken(AccessToken accessToken) {
    relativeLayout.setVisibility(View.GONE);
    relativeLayout1.setVisibility(View.VISIBLE);
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    //Iniciar sesión con una credencial
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        //metodo que se ejecuta al terminar el proceso
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (!task.isSuccessful()){
                //Ocurrio un error al realizar el logueo a firebase con facebook
                Utilities.exceptionFirebaseAdministrator(LoginActivity.this, task, LOG_TAG);
                LoginManager.getInstance().logOut();
            }else{
                pref.edit().putBoolean(getString(R.string.pref_logged_with_facebook),true).apply();
                pref.edit().putBoolean(getString(R.string.pref_logged_with_firebase),false).apply();
            }
            relativeLayout.setVisibility(View.VISIBLE);
            relativeLayout1.setVisibility(View.GONE);
        }
    });
}

fireAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();

            if(user != null){

//I try use SharedPreference and validate if is facebook login or other
                    startMainActivity();

            }

        }
    };

@Override
public void onStart() {
    super.onStart();
    //Cuando la clase empieza a "escuchar"
    firebaseAuth.addAuthStateListener(fireAuthStateListener);
}

@Override
public void onStop() {
    super.onStop();
    //Cuando la clase deja de "escuchar"
    firebaseAuth.removeAuthStateListener(fireAuthStateListener);
}

2 个答案:

答案 0 :(得分:0)

FirebaseAuth执行一项棘手的工作,当您启动应用程序firebase时,AuthStateListener首先执行以查找任何已更改的状态,即用户是否已登录或注销。
在您的代码中,您可以在启动时添加AuthStateListener,这就是为什么每次应用程序启动时都会覆盖其他方法并首先执行AuthStateListener。  在启动时添加AuthStateListener并在停止方法上删除它总是一个好习惯,这也是firebase工程师推荐的。 您正在执行此操作,在需要用户身份验证的应用程序中始终检查用户状态,然后执行任何对其进行的任务。

     Override
    public void onStart() {
super.onStart();
//Cuando la clase empieza a "escuchar"
firebaseAuth.addAuthStateListener(fireAuthStateListener);

}

答案 1 :(得分:0)

在代码中进行此更改

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        // this is the login layout change it to yours.
    setContentView(R.layout.activity_login);

    // START initialize_auth
    mAuth = FirebaseAuth.getInstance();
    // START auth_state_listener
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
              //check if user is  not null 
            if (user != null) {

// below code will triggers as soon as your facebook login task is successful                   


      // this will return provider as facebook,google,twitter,email ,etc

                String provider = user.getProviders().get(0) ;

                  pref.edit().putBoolean(getString(R.string.pref_logged_with_facebook), true).apply();
                  pref.edit().putBoolean(getString(R.string.pref_logged_with_firebase), false).apply();
  //I try use SharedPreference and validate if is facebook login or other
                startMainActivity();


            } else {
                // User is signed out
                Log.d(LOG_TAG, "user signed_out");
                // logout user and open login page .
            }
        }
    };


}

// [START on_start_add_listener]
@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

// [START on_stop_remove_listener]
@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}


private void handleFacebookAccessToken(AccessToken accessToken) {
    relativeLayout.setVisibility(View.GONE);
    relativeLayout1.setVisibility(View.VISIBLE);
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    //Iniciar sesión con una credencial
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        //metodo que se ejecuta al terminar el proceso
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (!task.isSuccessful()) {

                // If sign in fails, log message or go back to login page.         
                //If sign in succeeds the auth state listener will be  
               //notified and logic to handle the
              // signed in user can be handled in the listener.

                Utilities.exceptionFirebaseAdministrator(LoginActivity.this, task, LOG_TAG);
                LoginManager.getInstance().logOut();
            }
              // this will execute no matter whats happens ,
            relativeLayout.setVisibility(View.VISIBLE);
            relativeLayout1.setVisibility(View.GONE);
        }
    });
}

}