用户从FirebaseAuth等待身份验证时显示SplashScreen

时间:2018-02-16 15:25:01

标签: java android firebase-authentication

我试图在我的应用上显示启动画面,并且我设法使用构建意图的Handler和Runnable对象,并在2秒后将活动更改为我的登录活动使用意图构建

但是,现在我已经设置了Firebase身份验证。我试图构建符合预期行为的意图:
(用户签名 - >显示SplashScreen - >跳过LoginActivity)
(user notSignedIn - > show SplashScreen - > Show LoginActivity)
这是我目前正在处理的代码:

public class SplashScreenActivity extends AppCompatActivity {


    private FirebaseAuth mAuth = null;
    private FirebaseAuth.AuthStateListener mAuthListener;

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_splash_screen);

        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                mAuth = FirebaseAuth.getInstance();
                mAuthListener = new FirebaseAuth.AuthStateListener() {
                    @Override
                    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                        FirebaseUser user = firebaseAuth.getCurrentUser();
                        if (user != null) {
                            // User is signed in, send to mainmenu
                            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                            startActivity(new Intent(SplashScreenActivity.this, MainMenuActivity.class));
                        } else {
                            // User is signed out, send to register/login
                            startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
                        }
                    }
                };
            }
        }, SPLASH_DISPLAY_LENGTH);

    }
}

我已经省略了导入来缩短代码。问题是应用程序在启动画面中保持不变。

1 个答案:

答案 0 :(得分:1)

问题是您使用的是AuthStateListener。您真的只需要在不使用AuthStateListener的情况下执行以下操作:

             FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in, send to mainmenu
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    startActivity(new Intent(SplashScreenActivity.this, MainMenuActivity.class));
                } else {
                    // User is signed out, send to register/login
                    startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
                }