Firebase退出未执行

时间:2016-10-31 19:54:16

标签: android firebase firebase-authentication

我正在使用Firebase Authentification进行应用程序,但我遇到了问题。

Firebase FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)方法会自动在用户中签名。但我不想要这个,因为我需要在登录前进行电子邮件验证。

所以当我完成注册流程时,我实施了注销。你可以在下面找到我的代码。

我的问题是,当我从SignUpActivity返回LoginActivity时,来自LoginActivity的FirebaseAuthStateListener会检测到用户并转到MainActivity,这是我不想要的。

有没有人遇到同样的问题?

我目前正在用一面旗帜来解决这个问题,但我根本不喜欢它。在我退出之后,我不明白为什么FirebaseAuth会返回非空用户。

提前致谢,

阿德里安。

LoginActivity.java

public class LoginActivity extends AppCompatActivity {

    // Firebase stuff
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    // Facebook stuff
    private CallbackManager mCallbackManager;
    private Button mLoginButton;

    // Views stuff
    private LoginButton mLoginFbButton;
    private EditText mEmailTextField;
    private EditText mPasswordTextField;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        viewsSetup();
        firebaseSetUp();
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        if(mAuthListener != null)mAuth.removeAuthStateListener(mAuthListener);
    }

    @Override
    public void onResume() {
        super.onResume();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SIGNUP) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(getBaseContext(), getString(R.string.you_can_login), Toast.LENGTH_LONG).show();
            }
        }
        onResume();
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void firebaseSetUp() {
        mAuth = FirebaseAuth.getInstance();
        // Will be notified on login success
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null && !mFromSignup) {
                    // Login success is handled here and should not be handled anywhere else.
                    mLoginButton.setEnabled(true);

                    // Stop the progress dialog
                    mProgressDialog.dismiss();

                    toMainActivity();                     
                }
            }
        };
    }

private void signIn(AuthCredential credential) {

    // pops up the progress dialog
    mProgressDialog = ProgressDialog.show(this, getString(R.string.signing_in), null, true);

    // Will be notified when sign in request finish
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    // Do not handle authentification success here, on complete
                    // this will notify the Authentification Listener

                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(LoginActivity.this, getString(R.string.login_failed_message),
                                Toast.LENGTH_SHORT).show();
                        mProgressDialog.dismiss();
                        mLoginButton.setEnabled(true);
                    }
                }
            });
}

    private void viewsSetup() {
        mEmailTextField = (EditText) findViewById(R.id.email);
        mPasswordTextField = (EditText) findViewById(R.id.password);

        mLoginButton = (Button) findViewById(R.id.login_button);
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginButtonPressed();
            }
        });

        TextView mSignUp = (TextView) findViewById(R.id.create_an_account);
        mSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
                onPause();
                startActivityForResult(intent, REQUEST_SIGNUP);
            }
        });
        mProgressDialog = new ProgressDialog(this);
    }

    private void loginButtonPressed() {

        Log.d(TAG, "Login");

        if (!textFieldsFormatValid()) {
            Toast.makeText(LoginActivity.this, getString(R.string.check_text_fields),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

        mLoginButton.setEnabled(false);

        String email = mEmailTextField.getText().toString();
        String password = mPasswordTextField.getText().toString();

        signIn();
    }

    private boolean textFieldsFormatValid() {
        boolean valid = true;

        String email = mEmailTextField.getText().toString();
        String password = mPasswordTextField.getText().toString();

        if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            mEmailTextField.setError(getString(R.string.ask_valid_email));
            valid = false;
        } else {
            mEmailTextField.setError(null);
        }

        if (password.isEmpty()) {
            mPasswordTextField.setError(getString(R.string.required_field_msg));
            valid = false;
        } else {
            mPasswordTextField.setError(null);
        }

        return valid;
    }

    private void toMainActivity() {

        // Go to main activity
        startActivity(new Intent(LoginActivity.this, MainActivity.class));

        // Destroy activity to free memory we won't need it anymore until logout
        finish();
    }

}

SignUpActivity.java

public class SignUpActivity extends AppCompatActivity {


    // Used to determine when user finished signing up
    private boolean mFinished = false;

    // Firebase stuff
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    // Views stuff
    private EditText mEmail;
    private EditText mPassword;
    private EditText mPasswordConfirm;
    private EditText mFullname;
    private Button mSignUpButton;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        firebaseSetup();
        viewsSetup();
    }

    @Override
    public void onDestroy() {
        super.onStop();
        if(mAuthListener != null) mAuth.removeAuthStateListener(mAuthListener);
    }

    private void signUp() {
        mProgressDialog = ProgressDialog.show(this, getString(R.string.signing_up), null, true);

        if (!textFieldsFormatValid()) {
            Toast.makeText(getBaseContext(), getString(R.string.check_text_fields), Toast.LENGTH_LONG).show();
            return;
        }

        mSignUpButton.setEnabled(false);

        final String email = mEmail.getText().toString();
        final String password = mPassword.getText().toString();

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        // Do not handle authentification success here, on complete
                        // this will notify the Authentification Listener

                        if(!task.isSuccessful()) {
                            Toast.makeText(getBaseContext(), getString(R.string.signup_fail), Toast.LENGTH_LONG).show();
                            mSignUpButton.setEnabled(true);
                            mProgressDialog.dismiss();
                        } else {
                            mFinished = true;
                        }
                    }
                });
    }

    private void firebaseSetup() {
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
                final FirebaseUser user = firebaseAuth.getCurrentUser();
                if(user != null && !mFinished) {
                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                            .setDisplayName(mFullname.getText().toString())
                            .build();

                    user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            firebaseAuth.signOut();
                        }
                    });
                } else if (mFinished){
                    // Wait for logout here
                    firebaseAuth.removeAuthStateListener(this);
                    mSignUpButton.setEnabled(true);
                    mProgressDialog.dismiss();
                    setResult(RESULT_OK, null);
                    finish();
                }
            }
        };
        mAuth.addAuthStateListener(mAuthListener);
    }

    private void viewsSetup() {
        mEmail = (EditText) findViewById(R.id.email);
        mPassword = (EditText) findViewById(R.id.password);
        mPasswordConfirm = (EditText) findViewById(R.id.password_confirm);
        mFullname = (EditText) findViewById(R.id.full_name);
        mSignUpButton = (Button) findViewById(R.id.signup_button);
        TextView mLoginLink = (TextView) findViewById(R.id.to_login);

        mSignUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signUpButtonPressed();
            }
        });

        mLoginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mProgressDialog = new ProgressDialog(this);
    }

    private void signUpButtonPressed() {
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        if(!textFieldsFormatValid()) {
            Toast.makeText(this, R.string.toast_signup_failed, Toast.LENGTH_SHORT);
            return;
        }
        signUp();
    }


    private boolean textFieldsFormatValid() {
        boolean valid = true;

        String email = mEmail.getText().toString();
        String password = mPassword.getText().toString();
        String password2 = mPasswordConfirm.getText().toString();

        if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            mEmail.setError(getString(R.string.ask_valid_email));
            valid = false;
        } else {
            mEmail.setError(null);
        }

        if (password.isEmpty() || password.length() < 6 || password.length() > 10) {
            mPassword.setError(getString(R.string.password_err_msg));
            valid = false;
        } else {
            mPassword.setError(null);
        }

        if (password2.isEmpty() || password2.length() < 6 || password2.length() > 10) {
            mPasswordConfirm.setError(getString(R.string.password_err_msg));
            valid = false;
        } else if (!password2.equals(password)) {
            mPasswordConfirm.setError(getString(R.string.match_passwords));
            valid = false;
        } else {
            mPasswordConfirm.setError(null);
        }

        return valid;
    }
}

1 个答案:

答案 0 :(得分:0)

如果有人面临同样的问题一次,我就是这样解决的:

问题来自我从异步任务调用firebaseAuth.signOut()的事实(在user.updateProfile(profile)完成时)。我写错else if(mFinished)而不检查user == null是否出错。

导致某些情况导致我在没有退出的情况下回到LoginActivity