2017-04-11 46 views
1

我正尝试在android中使用facebook sdk和“user/password”选项进行firebase身份验证。我需要知道在启动MainActivity之前用户使用了哪种认证。执行命令firebase auth

几天前该代码用于正常工作,但我不得不抹去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); 
} 

回答

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

} 
+1

这是其他形式,它的工作原理谢谢(我如何投票反馈,我只现在点击向上箭头),但它似乎很奇怪,有时执行的顺序是onComplete,后来onAuthStateChanged。 有没有什么办法知道onAuthStateChanged方法,如果用户注册使用Facebook或电子邮件/密码步骤? –

+0

是的,你可以使用user.getProviders()。get(0)来检查提供者,返回类型是字符串,在if(user!= null)中使用。看到上面编辑的答案 –

+1

好的,谢谢很多糖! –

0

FirebaseAuth做一个棘手的工作,当你启动应用程序火力AuthStateListener执行第一寻找任何状态即改变,如果用户登录进入或退出。
在你的代码中,你在开始时添加AuthStateListener,这就是为什么每次你的应用程序启动时,它都会覆盖其他方法并首先执行AuthStateListener。 在启动时添加AuthStateListener并在停止方法中删除它总是一个好习惯,这也是Firebase工程师推荐的方法。 你做得很对,在需要用户验证的应用程序中总是检查用户状态,然后执行任何实现给他们的任务。

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

}

+0

但当authstate完成的,但不应该onConplete代码执行中的onComplete方法块代码被执行和完成时间触发authstatechanged? –

+0

这样做可以在您的活动的onCreate方法中写入firebaseAuthsatateListner方法。每当您的活动打开时,firebasauthstatListner将检查用户的状态。当用户尝试使用Facebook登录时,如果任务成功,则会通知验证状态侦听器,并且处理登录用户的逻辑可以在侦听器中处理。 –

+0

执行流程如下... firebase authStateListener(此时状态用户为空) - 您的Facebook登录oncomplete方法(如果任务成功) - 然后再次firebsaeauthstateListner。(此时状态转为用户!= null) –