且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我不使用Firebase身份验证时,如何使用Cloud Firestore中的SharedPreferences保存用户会话?

更新时间:2023-12-05 20:48:58

为获得***实践,请添加以下类

For best practice add the following class

public class PrefUtilities {

private SharedPreferences preferences;
Context context;


private PrefUtilities(Context context) {
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    this.context = context;
}


public static PrefUtilities with(Context context){
    return new PrefUtilities(context);
}


public void setUserLogin(boolean isUserLogedin){

    preferences.edit().putBoolean(context.getString(R.string.pref_key_user_status),isUserLogedin).apply();

}

public boolean isUserLogedin(){
    return preferences.getBoolean(context.getString(R.string.pref_key_user_status),false);
}


}

onCreate方法内检查登录状态

if(PrefUtilities.with(this).isUserLogedin()){

   Intent intent = new Intent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
}

passCheck方法内保存登录状态

private void passCheck(@NonNull DocumentSnapshot snapshot)
{
    final String uPass = tPassword.getText().toString();
    final String storedPass = snapshot.getString("password");
    if (storedPass != null && storedPass.equals(uPass))
    {

         PrefUtilities.with(this).setUserLogin(true);       

        Intent intent = new Intent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(SLogin.this, "Invalid Password!", Toast.LENGTH_LONG).show();
    }
}

用户注销时,使用波纹管方法更改SharedPreferences

When user logout use bellow method to change SharedPreferences

PrefUtilities.with(this).setUserLogin(false);

您还可以在PrefUtilities类中添加其他方法来保存用户电子邮件

You can also add other methods in PrefUtilities class saving user Email