调用super.onBackPressed() 将导航回上一个活动
我假设您使用的是 firebase google 身份验证。如果发生任何故障,以下 sn-ps 代码可能会帮助您导航回 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
}
} );
}
希望这个回答对你有帮助