Can I cancel the Firebase login process using only the Firebase SDK for Android?

I want users of my application to be able to cancel the Firebase login process while it is running. But I do not see direct handlers for this in the Firebase SDK. Accepted methods return Task<AuthResult>that cannot be undone. What is the best approach I can use to ensure cancellation? Is there a better way than developing additional canceled asynchronous tasks?

My code is exactly the same as in the firebase manual.

public class LoginActivity extends AppCompatActivity{
    private FirebaseAuth mFirebaseAuth;
    private FirebaseAuth.AuthStateListener mFirebaseAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(...);
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    onSignIn();
                } else {
                    // User is signed out
                    onSignOut();
                }
                // ...
            }
        };
    }

    private void signIn(String email, String password){
        mFirebaseAuth
            .signInWithEmailAndPassword(email, password) // returns noncancelable Task<AsyncResult>
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    // If sign in fails, display a message to the user. 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.
                    if (!task.isSuccessful()) {
                        Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
    }

    @Override
    public void onStart() {
        super.onStart();
        mFirebaseAuth.addAuthStateListener(mFirebaseAuthListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mFirebaseAuthListener != null) {
            mFirebaseAuth.removeAuthStateListener(mFirebaseAuthListener);
        }
    }
}
+4
source share

All Articles