Firebase Auth Back Button



我的android应用程序中的firebase身份验证没有后退按钮。如果onActivityResult产生取消结果,我希望能够导航回主活动。

如何启用此功能?我正在使用预构建的身份验证。

final int RC_SIGN_IN = 0;
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.PhoneBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()
);
Intent intent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTheme(R.style.FirebaseUI)
.build();
startActivityForResult(intent, RC_SIGN_IN);

调用super.onBackPressed()将导航回上一个活动

我想你使用的是firebase谷歌身份验证。如果发生任何故障,以下代码片段可能会帮助您导航回MainActivity。

要启动身份验证,请调用signIn()方法

如果发生任何API异常,onActivityResult()方法将导航回以前的活动

private static final int RC_SIGN_IN = 1;
private void signIn () {
Intent signInIntent = mGoogleSignInClient.getSignInIntent ();
startActivityForResult ( signInIntent, RC_SIGN_IN );
//Show user that authentication has started
}
@Override
public void onActivityResult ( int requestCode, int resultCode, Intent data ) {
super.onActivityResult ( requestCode, resultCode, data );
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent ( data );
try {
GoogleSignInAccount account = task.getResult ( ApiException.class );
assert account != null;
firebaseAuthWithGoogle ( account.getIdToken () );
} catch (ApiException e) {
Toast.makeText ( this, "Google Sign In failed", Toast.LENGTH_SHORT ).show ();
mGoogleSignInClient.signOut ();
mAuth.signOut ();
//Show user that authentication failed
//In your case navigate to MainActivity()
super.onBackPressed (); //Navigates to previous activity
}
}
}

以下代码检查返回的用户是否有效。如果没有导航回以前的活动

private void firebaseAuthWithGoogle ( String idToken ) {
AuthCredential credential = GoogleAuthProvider.getCredential ( idToken, null );
mAuth.signInWithCredential ( credential )
.addOnCompleteListener ( this, task -> {
if (task.isSuccessful ()) {
FirebaseUser user = mAuth.getCurrentUser ();
if (user != null) {
//Authenticated successfully
} else {
//Try to authenticate again
//This might not happen in most scenarios
signIn ();
}
} else {
Toast.makeText ( this, "Google Sign In failed", Toast.LENGTH_SHORT ).show ();
mGoogleSignInClient.signOut ();
mAuth.signOut ();
//Show user that authentication failed
//In your case navigate to MainActivity()
super.onBackPressed (); //Navigates to previous activity
}
} );
}

我希望这个答案能帮助你

相关内容

  • 没有找到相关文章

最新更新