Google登录后自动启动主要活动?

时间:2018-02-19 16:39:45

标签: android android-activity firebase-authentication google-signin

Google通过Firebase Auth登录后,我的应用程序的主要活动自动启动,即使我没有让任何intent启动它。

这是我的 LoginActivty.java

// Email Password
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
RelativeLayout LoginActivity;
private ProgressDialog mprogress;

//Database
private String userId;
FirebaseUser user;
DatabaseHelper myDb;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;

//Google Sign In
SignInButton mGoogleBtn;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiclient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

    mGoogleBtn = findViewById(R.id.googleSignIn);
    mGoogleBtn.setOnClickListener(this);

    mAuth = FirebaseAuth.getInstance();

    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    myDb = new DatabaseHelper(this);

    //Configure Google Sign In
    mprogress = new ProgressDialog(this);

    LoginActivity = findViewById(R.id.activity_login);
    mAuthListner = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            if (firebaseAuth.getCurrentUser() != null) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                mprogress.dismiss();
            }
        }
    };

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleApiclient = new GoogleApiClient.Builder(getApplicationContext())
            .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    mprogress.dismiss();
                    Toast.makeText(LoginActivity.this, "Connection failed.", Toast.LENGTH_SHORT).show();
                }
            }).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();

}

@Override
public void onClick(View view) {

    int btnId = view.getId();
    switch (btnId) {

        case R.id.googleSignIn:

            if (isNetworkAvailable()) {
                mprogress.setMessage("Signing In...");
                mprogress.show();
                mprogress.setCanceledOnTouchOutside(false);
                mprogress.setCancelable(false);
                signIn();

            } else {
                mprogress.dismiss();

            }

            break;
    }
}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListner);
}

private void signIn(){
    Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiclient);
    startActivityForResult(intent,RC_SIGN_IN);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode,resultCode,data);

    if(requestCode == RC_SIGN_IN) {

        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

        if(result.isSuccess()){
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        }else{
            mprogress.dismiss();
            Toast.makeText(LoginActivity.this, "Error",Toast.LENGTH_SHORT).show();
        }
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)

            .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
        @Override
        public void onSuccess(AuthResult authResult) {

           Intent intent = new Intent(LoginActivity.this, LoggedClientActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            mprogress.dismiss();

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

            mprogress.dismiss();
            Toast.makeText(LoginActivity.this, "Authentication failed.",Toast.LENGTH_SHORT).show();

        }
    });
} 

}

我想在成功验证后启动LogClientActivity.class,但它会启动MainActivity.class。我怎么能避免这种情况?

1 个答案:

答案 0 :(得分:1)

您正在使用FirebaseAuth.AuthStateListener,当身份验证状态发生变化时会触发,这实际上是开始您的主要活动,因此删除此侦听器

mAuthListner = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        // a change in login state is acquired 
        // now there is a current user available so 
        // it will start the main activity
        if (firebaseAuth.getCurrentUser() != null) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            mprogress.dismiss();
        }
    }
};

在身份验证状态发生变化的UI线程中调用voidonAuthStateChanged(FirebaseAuth auth)方法:

  • 听众注册后

  • 用户登录后

  • 当前用户退出时

  • 当前用户更改时