gpt4 book ai didi

java - android 在设备上保存非常小的数据的最佳方法

转载 作者:行者123 更新时间:2023-11-29 18:44:57 25 4
gpt4 key购买 nike

在我的应用程序启动 Activity 中,每次应用程序启动时我都需要检查三件事

  1. 应用版本
  2. 是用户登录
  3. 是否创建了用户帐户

我正在使用 Firebase 作为数据库,所以每次使用启动应用程序时,我都会在 Datachange 上检查数据库,然后根据返回结果和案例区域将用户发送到 Activity ,如下所示:

//check if newer version is available (Step 1)
if (appVersionMatch) {
CheckLogin();
} else {
//Take user to appstore for app update
}


// (Step 2)
public void CheckLogin() {
if (userLogin) {
CheckUserExist()
} else {
//Show user Login activity
}
}


// (Step 3)
public void CheckUserExist() {
if (user.exist()) {
//Go To main Activity
} else {
//Go To Register activity
}
}

这个流程工作正常,但总是需要一些时间来检查所有这三件事..我在想我是否可以在第一次登录和帐户创建信息时保存,这样就不需要再次检查,这样用户就可以去为了更快地进行主要 Activity ,我尝试按照以下方式进行,但没有按预期工作:

 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = pref.edit();
boolean isLoogenIn = pref.getBoolean("userLoginCheck", false);

最佳答案

这就是我使用 SharedPreferences 的方式。

首先创建一个单独的类(我用它来保存其他信息,如 url、常量等),在其中创建一个 SharedPreferences

public class project_constants {
private static String PREF_NAME = "project_pref";

private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}

public static boolean getUserLogin(Context context) {
return getPrefs(context).getBoolean("login", false);
}

public static void setUserLogin(Context context, boolean input) {
SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putBoolean("login", input);
editor.apply();
}

现在当用户登录时,您应该使用 project_constants.setuserLogin(getApplicationContext,True);

现在当你想检查用户是否已登录时,你可以使用 project_constants.getuserLogin(getApplicationContext); ,如果是,则用户已登录,否则否。

关于java - android 在设备上保存非常小的数据的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52203679/

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