FireBase身份验证身份验证状态已更改

时间:2016-05-30 21:15:56

标签: java android android-intent firebase

我希望能够根据用户的登录状态是否发生变化将意图传递给活动

我必须在LoginActivity的OnCreate方法中跟随AuthStateListener

如果用户已登录,则我希望将其转发到MainActivity

但是,如果用户已注销,则需要转到LoginActivity

问题出现在他们退出时,它陷入无限循环,不断向LoginActivity发射意图。

当auth状态发生变化时,是否有任何方法可以告知用户的位置(哪个活动)。这样我就可以在if语句中放置已注销的intent调用来检查它们是否已经在LoginAcitvity,从而阻止了循环

   mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Intent intent = new Intent(getBaseContext(), MainActivity.class);
                //intent.putExtra("EXTRA_SESSION_ID", sessionId);
                startActivity(intent);
                Log.d("LOG_Login", "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                String className = this.getClass().getSimpleName();
                if (!(className == "LoginActivity")) {
                    Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                    //intent.putExtra("EXTRA_SESSION_ID", sessionId);
                    startActivity(intent);
                }

                Log.d("LOG_Login", "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };

1 个答案:

答案 0 :(得分:0)

答案在最后是相当合乎逻辑的

我将Firebase Auth调用移动到我的主要活动并修改了进程以将意图转发到Login活动而不是相反。这避免了任何无限循环

mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                  //  Intent intent = new Intent(getBaseContext(), MainActivity.class);
                    //intent.putExtra("EXTRA_SESSION_ID", sessionId);
                  //  startActivity(intent);
                   // Log.d("LOG_Login", "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    String className = this.getClass().getName();
                    if (!(className == "LoginActivity")) {
                         Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                       // intent.putExtra("EXTRA_SESSION_ID", sessionId);
                         startActivity(intent);
                    }

                    Log.d("LOG_Login", "onAuthStateChanged:signed_out");
                }
                // ...
            }
        };

        mAuth.addAuthStateListener(mAuthListener);