现在我正在尝试创建一个 Android 应用程序。我想要的是,我在手机上登录了该应用程序,每当我从游戏商店获得该应用程序的更新时,它都应该始终登录。我如何在 SharedPreference 和 RealmDB 中创建它。
任何建议都会对我有帮助。
谢谢
最佳答案
首先,创建 Preferences.java(帮助程序):
package ru.str.proglot.visitor.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class Preferences {
@SuppressWarnings("unchecked")
public static <T> T getValue(Context context, String key, T defaultValue) {
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(context);
T resultValue = null;
if (defaultValue instanceof Boolean)
resultValue = (T) Boolean.valueOf(sPref.getBoolean(key, (Boolean) defaultValue));
else if (defaultValue instanceof Float)
resultValue = (T) Float.valueOf(sPref.getFloat(key, (Float) defaultValue));
else if (defaultValue instanceof Integer)
resultValue = (T) Integer.valueOf(sPref.getInt(key, (Integer) defaultValue));
else if (defaultValue instanceof Long)
resultValue = (T) Long.valueOf(sPref.getLong(key, (Long) defaultValue));
else if (defaultValue instanceof String)
resultValue = (T) sPref.getString(key, (String) defaultValue);
return resultValue;
}
public static <T> void setValue(Context context, String key, T value) {
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sPref.edit();
if (value instanceof Boolean)
editor.putBoolean(key, (Boolean) value);
else if (value instanceof Float)
editor.putFloat(key, (Float) value);
else if (value instanceof Integer)
editor.putInt(key, (Integer) value);
else if (value instanceof Long)
editor.putLong(key, (Long) value);
else if (value instanceof String)
editor.putString(key, (String) value);
editor.apply();
}
public static void remove(Context context, String key) {
PreferenceManager.getDefaultSharedPreferences(context).edit().remove(key).apply();
}
public static void clear(Context context ) {
PreferenceManager.getDefaultSharedPreferences(context).edit().clear().apply();
}
}
接下来,从任何地方保存信息:
Preferences.setValue(this, "name", "Ivan");
并获取值(value):
Preferences.getValue(this, "name", "");
关于java - 当应用程序从Play商店强制更新时,如何保持Android应用程序始终处于登录状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58723765/