[英]android best way to save very tiny data on device
在我的應用程序啟動活動中,每次啟動應用程序時,我需要檢查三件事
我將Firebase用於數據庫,因此每次使用啟動應用程序時,我都要在Datachange上檢查數據庫,然后根據返回結果和案例區域將用戶發送到活動中,如下所示:
//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
}
}
並且此流程工作正常,但始終需要花費一些時間來檢查所有這三件事。.我在想是否可以保存首次登錄和帳戶創建信息,因此無需再次檢查,因此用戶可以進入主要活動我嘗試用以下方法更快地執行此操作,但無法按預期工作:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = pref.edit();
boolean isLoogenIn = pref.getBoolean("userLoginCheck", false);
從Firebase准備好數據后,您應該首次使用以下方法將數據保存在SharedPreference中:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("userLoginCheck", false);
editor.commit();
然后,您可以使用以下方法獲取下一次的偏好值:
boolean isLoogenIn = pref.getBoolean("userLoginCheck", true);
這就是我使用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);
,如果是這樣,則用戶已登錄,否則,否。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.