gpt4 book ai didi

android - 尝试使用 Android SharedPreferences 维护登录状态

转载 作者:行者123 更新时间:2023-11-29 14:40:20 24 4
gpt4 key购买 nike

我有一个扩展应用程序的类:

public class myApp extends Application {

public static boolean isUserLoggedIn = false;
public static String username = null;
public static SharedPreferences logInState;

public static boolean userLogin() {

return myApp.isUserLoggedIn = true;
}

public static boolean userLogout() {

return myApp.isUserLoggedIn = false;
}

public static void setUser(String s) {

myApp.username = s;
}

@Override
public void onCreate() {
super.onCreate();
String PREFS_NAME = "LoginState";
logInState = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
}

}

我觉得我已经完成了一半,只需使用一个 true/false 变量来指示用户是否需要在每次启动应用程序时登录。当然,我也会将用户名存储在 SharedPreference 中,但是为了这个问题,为了简单起见,我只讨论一个。 (请记住,用户无需登录即可启动应用程序,但功能有限——他们可以通过溢出菜单登录)。

当用户首次登录时,我希望将首选项设置为 true。 如何从 Activity 中调用此类扩展应用程序?

目前我有一个成功的登录尝试:

myApp.userLogin();
myApp.setUser(UsernameLogin);
// would like to set SharedPreference var to true here?

最佳答案

要维护用户登录状态,首先创建一个名为 PreferenceData 的类。当用户成功登录时,然后在共享首选项中设置一个变量为 true 并注销然后为 false。

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

public class PreferenceData
{
static final String PREF_LOGGEDIN_USER_EMAIL = "logged_in_email";
static final String PREF_USER_LOGGEDIN_STATUS = "logged_in_status";

public static SharedPreferences getSharedPreferences(Context ctx)
{
return PreferenceManager.getDefaultSharedPreferences(ctx);
}

public static void setLoggedInUserEmail(Context ctx, String email)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_LOGGEDIN_USER_EMAIL, email);
editor.commit();
}

public static String getLoggedInEmailUser(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_LOGGEDIN_USER_EMAIL, "");
}

public static void setUserLoggedInStatus(Context ctx, boolean status)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_LOGGEDIN_STATUS, status);
editor.commit();
}

public static boolean getUserLoggedInStatus(Context ctx)
{
return getSharedPreferences(ctx).getBoolean(PREF_USER_LOGGEDIN_STATUS, false);
}

public static void clearLoggedInEmailAddress(Context ctx)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.remove(PREF_LOGGEDIN_USER_EMAIL);
editor.remove(PREF_USER_LOGGEDIN_STATUS);
editor.commit();
}
}

现在在 Activity 中你可以像下面这样调用它的方法。

PreferenceData.setUserLoggedInStatus(this,true);   // For set user loggedin status
PreferenceData.getUserLoggedInStatus(this); // Get User Logged In status . true = login

关于android - 尝试使用 Android SharedPreferences 维护登录状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11894447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com