Android在设备上保存非常小的数据的最佳方法 [英] android best way to save very tiny data on device
问题描述
在我的应用程序启动活动中,每次启动应用程序时我都需要检查三件事
in my application launching activity i need to check three things every time app is started
- 应用版本
- 是用户登录名
- 是否创建了用户帐户
我在数据库中使用 Firebase ,因此每次使用启动应用程序时,我都要在 Datachange 上检查数据库,然后根据返回结果和案例区域(如下所示)将用户转到活动中:
I am using Firebase for database so every time when use start app i check in DB on Datachange and then send user to activity according return results and case area like below:
//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
}
}
,此流程工作正常,但始终需要花费一些时间来检查所有这三件事..我在想是否可以保存首次登录和帐户创建信息,因此无需再次检查,因此用户可以继续加快主要活动的速度,我尝试使用以下方法进行操作,但未按预期工作:
and this flow works fine but it always take some time to check all these three thing..i was thinking if i could save on first login and on account create info so there is no need to check it again so user can go to main activity faster i tried do it with following but is not work as expected:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = pref.edit();
boolean isLoogenIn = pref.getBoolean("userLoginCheck", false);
推荐答案
这是我使用 SharedPreferences
的方式.
首先创建一个单独的类(我用它来保存其他信息,如url,常量等.)在其中创建一个 SharedPreferences
.
First create a separate class( I use it to save other informations like url, constants etc.) In that create a 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);
.
Now when the user log's in, you should use project_constants.setuserLogin(getApplicationContext,True);
.
现在,当您要检查用户是否已登录时,可以使用 project_constants.getuserLogin(getApplicationContext);
,如果是,则表明用户已登录,否则.
Now when you want to check whether the user has logged in or not, you can use project_constants.getuserLogin(getApplicationContext);
, if that's true, the user is logged in, else no.
这篇关于Android在设备上保存非常小的数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!