【问题标题】:Android - right way to store a value for repeated use?Android - 存储重复使用值的正确方法?
【发布时间】:2016-11-30 03:51:14
【问题描述】:

我的应用程序中有一项服务始终在运行,但是当手机空闲一段时间(可能应用程序正在关闭)时,全局静态变量似乎会被重置。请让我知道存储重复使用值的最佳方法,可能每 2-5 分钟一次。

如果在 2-5 分钟内访问一次,使用 SharedPreference 会导致高开销吗?

感谢您的帮助。

【问题讨论】:

  • 如果你有更多的值然后存储在数据库中,否则会话就足够了
  • 我只需要存储一个值。使用 SharedPreference 非常频繁地访问该值(每分钟一次)会导致高开销吗?
  • 不,你可以使用 SharedPreference
  • 可以经常访问
  • 太好了,谢谢。如果您希望我接受,请添加为答案。

标签: android sharedpreferences


【解决方案1】:

SharedPreference 是最佳选择。

public class AppPreference {
public static final String APP_NAME_KEY= "your_app_name";
public static final String SAMPLE_KEY = "sample";

public SharedPreferences preferences;
private SharedPreferences.Editor editor;

private String sample;

public AppPreference(Context context) {
        preferences = context.getSharedPreferences(APP_NAME_KEY, Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

public void setSample(String sample) {
    this.sample= sample;
    editor.putString(SAMPLE_KEY , this.sample);
    editor.commit();
}

public String getSample() {
        return preferences.getString(SAMPLE_KEY, null);
    }
}

您可以根据需要使用整数、浮点数、布尔值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多