📌  相关文章
📜  在 Android 中使用 Firebase 进行用户身份验证

📅  最后修改于: 2022-05-13 01:55:21.183000             🧑  作者: Mango

在 Android 中使用 Firebase 进行用户身份验证

Firebase 是一个移动和 Web 应用程序开发平台。它提供 Web 应用程序或移动应用程序可能需要的服务。 Firebase 提供电子邮件和密码身份验证,无需为用户身份验证构建后端的任何开销。

firebase 用户身份验证的步骤是:

  • 第1步:
    在 android studio 上创建一个新项目或打开一个现有项目,您要在其中添加身份验证并将 firebase 添加到该 android 应用程序。添加 firebase 的步骤在以下链接中有很好的解释:https://www.geeksforgeeks.org/添加-firebase-to-android-app/
  • 第2步:
    转到 Firebase 控制台 (http://console.firebase.google.com/) 导航到您的应用程序,然后在身份验证选项卡下,启用电子邮件/通过身份验证。
  • 第三步: activity_registration.xml
    这是您的注册活动。它有两个 EditTexts、一个 TextView、一个按钮和一个进度条。所有这些视图都包含在垂直方向的线性布局中。 EditTexts 用于从用户那里获取电子邮件和密码。按钮用于填写用户名和密码后的注册目的。
    注册活动(activity_registration)的完整xml代码是:
    activity_registration.xml
    
      
    
    
      
        
        
      
        
        
      
        
        
      
        
        


    RegistrationActivity.java
    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.AuthResult;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
      
    public class RegistrationActivity extends AppCompatActivity {
      
        private EditText emailTextView, passwordTextView;
        private Button Btn;
        private ProgressBar progressbar;
        private FirebaseAuth mAuth;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_registration);
      
            // taking FirebaseAuth instance
            mAuth = FirebaseAuth.getInstance();
      
            // initialising all views through id defined above
            emailTextView = findViewById(R.id.email);
            passwordTextView = findViewById(R.id.passwd);
            Btn = findViewById(R.id.btnregister);
            progressbar = findViewById(R.id.progressbar);
      
            // Set on Click Listener on Registration button
            Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    registerNewUser();
                }
            });
        }
      
        private void registerNewUser()
        {
      
            // show the visibility of progress bar to show loading
            progressbar.setVisibility(View.VISIBLE);
      
            // Take the value of two edit texts in Strings
            String email, password;
            email = emailTextView.getText().toString();
            password = passwordTextView.getText().toString();
      
            // Validations for input email and password
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter email!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter password!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            // create new user or register new user
            mAuth
                .createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener() {
      
                    @Override
                    public void onComplete(@NonNull Task task)
                    {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(),
                                           "Registration successful!",
                                           Toast.LENGTH_LONG)
                                .show();
      
                            // hide the progress bar
                            progressBar.setVisibility(View.GONE);
      
                            // if the user created intent to login activity
                            Intent intent
                                = new Intent(RegistrationActivity.this,
                                             MainActivity.class);
                            startActivity(intent);
                        }
                        else {
      
                            // Registration failed
                            Toast.makeText(
                                     getApplicationContext(),
                                     "Registration failed!!"
                                         + " Please try again later",
                                     Toast.LENGTH_LONG)
                                .show();
      
                            // hide the progress bar
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
        }
    }


    activity_login.xml
    
    
      
    
          
        
        
              
        
        
              
        
        
              
        
        


    LoginActivity.java
    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.AuthResult;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
      
    public class LoginActivity extends AppCompatActivity {
      
        private EditText emailTextView, passwordTextView;
        private Button Btn;
        private ProgressBar progressbar;
      
        private FirebaseAuth mAuth;
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            // taking instance of FirebaseAuth
            mAuth = FirebaseAuth.getInstance();
      
            // initialising all views through id defined above
            emailTextView = findViewById(R.id.email);
            passwordTextView = findViewById(R.id.password);
            Btn = findViewById(R.id.login);
            progressbar = findViewById(R.id.progressBar);
      
            // Set on Click Listener on Sign-in button
            Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    loginUserAccount();
                }
            });
        }
      
        private void loginUserAccount()
        {
      
            // show the visibility of progress bar to show loading
            progressbar.setVisibility(View.VISIBLE);
      
            // Take the value of two edit texts in Strings
            String email, password;
            email = emailTextView.getText().toString();
            password = passwordTextView.getText().toString();
      
            // validations for input email and password
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter email!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter password!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            // signin existing user
            mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(
                    new OnCompleteListener() {
                        @Override
                        public void onComplete(
                            @NonNull Task task)
                        {
                            if (task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(),
                                               "Login successful!!",
                                               Toast.LENGTH_LONG)
                                    .show();
      
                                // hide the progress bar
                                progressBar.setVisibility(View.GONE);
      
                                // if sign-in is successful
                                // intent to home activity
                                Intent intent
                                    = new Intent(LoginActivity.this,
                                                 MainActivity.class);
                                startActivity(intent);
                            }
      
                            else {
      
                                // sign-in failed
                                Toast.makeText(getApplicationContext(),
                                               "Login failed!!",
                                               Toast.LENGTH_LONG)
                                    .show();
      
                                // hide the progress bar
                                progressbar.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    }


    activity_main.xml
    
          
        
    


    MainActivity.java
    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    public class MainActivity extends AppCompatActivity {
      
        private TextView geeksforgeeks;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
      
            // initialising all views through id defined above
            geeksforgeeks = findViewById(R.id.gfg);
            geeksforgeeks.setText(
                "GeeksForGeeks(Firebase Authentication)");
        }
    }


  • 第 4 步:注册活动。Java
    • 现在轮到注册活动的Java代码了。
    • 在此,我们有一个附加到按钮的一键式侦听器。单击按钮时,将调用 registerNewUser()。在此方法中,检查电子邮件和密码中的任何参数是否不为空。如果是这种情况,则会显示一条错误消息。如果两个 Edit 文本都有数据,则调用 createUserWithEmailAndPassword() 方法。
    • 要注册一个新用户,使用createUserWithEmailAndPassword()函数,该函数接收两个参数,即您要注册的电子邮件和密码。在 createUserWithEmailAndPassword() 方法中,检查任务是否成功。如果任务成功,则用户将被定向到 MainActivity 或仪表板,否则会显示一条带有“注册失败”的 Toast 消息。
    • 对于用户身份验证,我们必须参考 FirebaseAuth。我们可以使用 getInstance函数参考。代码片段是:
      FirebaseAuth mAuth = FirebaseAuth.getInstance();

    注册活动的Java代码是:

    注册活动。Java

    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.AuthResult;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
      
    public class RegistrationActivity extends AppCompatActivity {
      
        private EditText emailTextView, passwordTextView;
        private Button Btn;
        private ProgressBar progressbar;
        private FirebaseAuth mAuth;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_registration);
      
            // taking FirebaseAuth instance
            mAuth = FirebaseAuth.getInstance();
      
            // initialising all views through id defined above
            emailTextView = findViewById(R.id.email);
            passwordTextView = findViewById(R.id.passwd);
            Btn = findViewById(R.id.btnregister);
            progressbar = findViewById(R.id.progressbar);
      
            // Set on Click Listener on Registration button
            Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    registerNewUser();
                }
            });
        }
      
        private void registerNewUser()
        {
      
            // show the visibility of progress bar to show loading
            progressbar.setVisibility(View.VISIBLE);
      
            // Take the value of two edit texts in Strings
            String email, password;
            email = emailTextView.getText().toString();
            password = passwordTextView.getText().toString();
      
            // Validations for input email and password
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter email!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter password!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            // create new user or register new user
            mAuth
                .createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener() {
      
                    @Override
                    public void onComplete(@NonNull Task task)
                    {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(),
                                           "Registration successful!",
                                           Toast.LENGTH_LONG)
                                .show();
      
                            // hide the progress bar
                            progressBar.setVisibility(View.GONE);
      
                            // if the user created intent to login activity
                            Intent intent
                                = new Intent(RegistrationActivity.this,
                                             MainActivity.class);
                            startActivity(intent);
                        }
                        else {
      
                            // Registration failed
                            Toast.makeText(
                                     getApplicationContext(),
                                     "Registration failed!!"
                                         + " Please try again later",
                                     Toast.LENGTH_LONG)
                                .show();
      
                            // hide the progress bar
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
        }
    }
    

  • 第五步: activity_login.xml
    现在在注册活动之后,我们必须创建登录活动。登录活动的布局类似于注册活动,有两个编辑文本,一个按钮,一个用于标题的文本视图都包含在垂直方向的线性布局中。这是 xml 文件的完整代码活动登录.xml:

    活动登录.xml

    
    
      
    
          
        
        
              
        
        
              
        
        
              
        
        
  • 第 6 步:登录活动。Java
    这里的代码与 RegistrationActivity 非常相似,但使用signInWithEmailAndPassword()函数进行登录,该函数将电子邮件和密码作为参数,如果具有电子邮件和密码的用户存在,那么您将被重定向到 mainactivity 或 Dashboard.Inside signInWithEmailAndPassword() 方法,任务检查成功。如果任务成功,则将用户定向到 Mainactivity 或仪表板,否则将显示一条带有“登录失败”的 Toast 消息。登录活动的Java代码是:

    登录活动。Java

    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.AuthResult;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
      
    public class LoginActivity extends AppCompatActivity {
      
        private EditText emailTextView, passwordTextView;
        private Button Btn;
        private ProgressBar progressbar;
      
        private FirebaseAuth mAuth;
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            // taking instance of FirebaseAuth
            mAuth = FirebaseAuth.getInstance();
      
            // initialising all views through id defined above
            emailTextView = findViewById(R.id.email);
            passwordTextView = findViewById(R.id.password);
            Btn = findViewById(R.id.login);
            progressbar = findViewById(R.id.progressBar);
      
            // Set on Click Listener on Sign-in button
            Btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {
                    loginUserAccount();
                }
            });
        }
      
        private void loginUserAccount()
        {
      
            // show the visibility of progress bar to show loading
            progressbar.setVisibility(View.VISIBLE);
      
            // Take the value of two edit texts in Strings
            String email, password;
            email = emailTextView.getText().toString();
            password = passwordTextView.getText().toString();
      
            // validations for input email and password
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter email!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(),
                               "Please enter password!!",
                               Toast.LENGTH_LONG)
                    .show();
                return;
            }
      
            // signin existing user
            mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(
                    new OnCompleteListener() {
                        @Override
                        public void onComplete(
                            @NonNull Task task)
                        {
                            if (task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(),
                                               "Login successful!!",
                                               Toast.LENGTH_LONG)
                                    .show();
      
                                // hide the progress bar
                                progressBar.setVisibility(View.GONE);
      
                                // if sign-in is successful
                                // intent to home activity
                                Intent intent
                                    = new Intent(LoginActivity.this,
                                                 MainActivity.class);
                                startActivity(intent);
                            }
      
                            else {
      
                                // sign-in failed
                                Toast.makeText(getApplicationContext(),
                                               "Login failed!!",
                                               Toast.LENGTH_LONG)
                                    .show();
      
                                // hide the progress bar
                                progressbar.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    }
    

  • 第七步: activity_main.xml
    这是仪表板活动,其中包含相对布局中的简单文本视图。代码如下:

    activity_main.xml

    
          
        
    
    
  • 第 8 步:主要活动。Java
    MainActivity 包含用户在登录或注册后重定向到的仪表板代码。

    主要活动。Java

    package com.geeksforgeeks.firebaseuserauthentication;
      
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.view.View;
    import android.widget.Toast;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
      
    public class MainActivity extends AppCompatActivity {
      
        private TextView geeksforgeeks;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
      
            // initialising all views through id defined above
            geeksforgeeks = findViewById(R.id.gfg);
            geeksforgeeks.setText(
                "GeeksForGeeks(Firebase Authentication)");
        }
    }
    

输出:

  • 注册新用户

    注册包含电子邮件和密码字段的活动

  • 注册成功

    注册成功时的主要活动

  • 新的用户数据已成功存储在 firebase 上。注册成功步骤后,您可以在应用程序的 firebase 控制台上看到注册用户。
    注册用户

    注册用户

  • 用户尝试使用刚刚注册的凭据登录

    带有电子邮件和密码字段的登录活动