首页 > 解决方案 > 使用 Firebase 身份验证的正确方法是什么?

问题描述

我刚刚开始使用 FirebaseUI 电子邮件/密码身份验证。

我的应用程序非常简单,到目前为止它由 1 个活动组成,该活动使用 TabLayout 包含 3 个片段,如下所示:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        TabsAdapter adapter = new TabsAdapter(this, getSupportFragmentManager());   
        viewPager.setAdapter(adapter);     
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        }
    }

在 Firebase 助手上,它显示我需要检查用户是否已登录,在 onStart 中:

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}

然后,助手显示如何注册和登录用户,但它没有显示它应该进入活动的哪个部分:onCreateonStart?

*这是注册码:

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

*这是登录代码

mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

我很困惑,假设我目前有工作应用程序,上面提供的代码,现在的工作流程是什么?我是否需要在 Mainactivity 中制作此注册/登录代码,然后,而不是updateUI(null);Firebase 助手提供的伪代码,我应该只使用 firebase auth 代码制作一个新的“主要活动”,然后使用意图将用户发送到当前的主要活动,它将被重命名为“SignedInActivity”之类的东西,或者所有事情都在同一个当前活动中完成?

**编辑:澄清我的意思:我目前有 MainActivity。我需要:

1)将当前的MainActivity改为SignedInActivity,然后将当前的MainActivity替换为Firebase的activity,登录成功后发送intent到SignedInActivity

或者

2) 使用 Firebase 代码修改当前 MainActivity 以便我仍然拥有当前 MainActivity 以及 Firebase 的额外代码?

我也很困惑,所以希望我的帖子可以理解

标签: androidfirebasefirebase-authenticationfirebaseui

解决方案


你真的应该查看Android Lifecycle。重要的是要知道回调(onCreate、onStart、onResume 等)何时被调用,然后您可以自行决定在何处实现代码。

在您的情况下,我会创建一个 LoginActivity,您还可以在其中使用“createUserWithEmailAndPassword()”注册一个新的个人资料并使用已创建的帐户登录。如果成功,您可以启动 MainActivity。

mAuth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success, update UI with the signed-in user's information
               Log.d(TAG, "signInWithEmail:success");

               Intent intent = new Intent(this, MainActivity.class);
               startActivity(intent);

            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInWithEmail:failure", task.getException());
                Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
            }

            // ...
        }
    });

然后在 MainActivity 的 onCreate 回调中,您可以仔细检查用户是否登录:

@Override
public void onCreate() {
    super.onCreate();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if(currentUser != null) {
        updateUI(currentUser);
    } else {
        //intent back to login screen
    }
}

推荐阅读