如何自动将两种不同类型的用户登录到不同的活动而不必再次登录? [英] How to log in two different types of users to different activities automatically without having to log in again?

查看:79
本文介绍了如何自动将两种不同类型的用户登录到不同的活动而不必再次登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase作为后端构建此android应用程序.它需要两组不同的用户,一组讲师和一组学生.但是有一个问题.我希望已经登录并关闭应用程序的学生在学生再次打开应用程序时自动登录到其他家庭活动.同样适用于讲师.我该如何实现?有人可以帮忙提供示例代码吗?我知道firebase用于自动将用户登录到应用程序首页的功能,但是如果一个人是学生或讲师,我如何指定应该自动打开的页面?

There's this android application I'm building with Firebase as the backend. It requires two different sets of users, a set of lecturers and a set of students. There's an issue however. I would want a student that has already logged in and closed the app to automatically log in to a different home activity when the student opens the app again. Same should apply to the lecturers. How do I achieve that? Can someone help with a sample code? I know about the functionality that firebase uses to automatically log in users to the homepage of an app but how do I specify the page that should automatically open if one is a student or a lecturer?

我的登录活动

public class LoginActivity extends AppCompatActivity {

private TextInputLayout mLoginEmail;
private TextInputLayout mLoginPassword;

private ProgressDialog mLoginProgress;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference jLoginDatabase, student_token_reference, lecturer_token_reference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mLoginProgress = new ProgressDialog(this);

    mAuth = FirebaseAuth.getInstance();

    if (mAuth.getCurrentUser() != null) {
        Intent main_intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(main_intent);
    }


    mLoginEmail = findViewById(R.id.login_email);
    mLoginPassword = findViewById(R.id.login_password);

    Button mLogin_btn = findViewById(R.id.login_btn);

    TextView msignup = findViewById(R.id.sign_up_text);
    msignup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent gotosignup = new Intent(LoginActivity.this, ChoiceActivity.class);
            startActivity(gotosignup);
        }
    });

    mLogin_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String email = mLoginEmail.getEditText().getText().toString();
            String password = mLoginPassword.getEditText().getText().toString();

            if (!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password)) {

                mLoginProgress.setTitle("Logging in user");
                mLoginProgress.setMessage("Please wait while we log you in...");
                mLoginProgress.setCanceledOnTouchOutside(false);
                mLoginProgress.show();

                loginUser(email, password);

            } else {
                Toast.makeText(LoginActivity.this, "Please fill in credentials first", Toast.LENGTH_LONG).show();
            }


        }
    });

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {

            } else {
                // User is signed out
            }
            // ...
        }
    };

}

private void loginUser(String email, String password) {
    mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (task.isSuccessful()) {

                        FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
                        String RegisteredUserID = currentUser.getUid();

                        jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(RegisteredUserID);

                        jLoginDatabase.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                String userType = dataSnapshot.child("userType").getValue().toString();
                                if (userType.equals("Lecturers")) {

                                    mLoginProgress.dismiss();

                                    Intent intentResident = new Intent(LoginActivity.this, LecturerMainActivity.class);
                                    intentResident.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intentResident);
                                    finish();

                                } else if (userType.equals("Students")) {

                                    mLoginProgress.dismiss();

                                    Intent intentMain = new Intent(LoginActivity.this, MainActivity.class);
                                    intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intentMain);
                                    finish();

                                } else {

                                    mLoginProgress.hide();
                                    Toast.makeText(LoginActivity.this, "Failed to authenticate user", Toast.LENGTH_SHORT).show();

                                }
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });
                    }
                }
            });
}


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

@Override
protected void onStop() {
    super.onStop();
}

@Override
public void onBackPressed() {
    moveTaskToBack(true);
    super.onBackPressed();
}
}

推荐答案

这是我用来解决相同问题的一种技巧. (请注意,此方法可能存在安全问题,我更喜欢使用Firebase Admin使用Firebase自定义声明.)

This is a hack I used to solve the same issue. (Please note that this method may have security issues and I prefer using Firebase Custom Claims using Firebase Admin).

创建一个LoginActivity,使用该用户登录用户,并在登录后在UserTypeSelectorActivity中访问用户类型(管理员,学生,职员,有偿内容),并形成此活动,您可以将用户类型传递给其他使用Intent数据或共享首选项的活动(根据您的应用,您会感觉更好)

Create a LoginActivity using which you log in the user and after logging in, access the user type(admin, student, staff, paid whatever) in an UserTypeSelectorActivity and form this activity you can pass the user type to other activities using Intent data or shared preferences (which you feel better according to your app)

public class UserTypeSelectorActivity extends AppCompatActivity {

    //  Firebase Variables
    FirebaseUser firebaseUser;
    FirebaseDatabase firebaseDatabase;
    DatabaseReference firebaseDatabaseReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("Activity Name", getLocalClassName());

        //  Initializing Firebase Variables
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        firebaseDatabase = FirebaseDatabase.getInstance();
        firebaseDatabaseReference = firebaseDatabase.getReference();

        if (firebaseUser != null) {
            firebaseDatabaseReference.child("my_app_user").child(firebaseUser.getUid())
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            //  Check user type and redirect accordingly
                            if (dataSnapshot.child("admin").exists()) {
                                Boolean admin = dataSnapshot.child("admin")
                                        .getValue().toString().equals("true");
                                if (admin) {
                                    startActivity(new Intent(UserTypeSelectorActivity.this,
                                            AdminActivity.class));
                                    finish();
                                } else {
                                    startActivity(new Intent(UserTypeSelectorActivity.this,
                                            ClientActivity.class));
                                    finish();
                                }
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                        }
                    });
        }
    }
}

注意:一项警告性警告,称这不是适当的解决方案.这就是我在应用程序中实现的方式.

Note: A precautionary warning that this is not a proper solution. It is how I have implemented in my app.

这篇关于如何自动将两种不同类型的用户登录到不同的活动而不必再次登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆