【问题标题】:StrictModeDiskReadViolation whenStrictModeDiskReadViolation 时
【发布时间】:2012-10-30 16:18:26
【问题描述】:

我正在尝试使用 SharedPreferences 来存储我的应用的一些用户设置。我的 Activity.onCreate 方法中有这段代码:

sharedPreferences = context.getSharedPreferences("MMPreferences", 0);
soundOn = sharedPreferences.getBoolean("soundOn", true);

但它给了我这个错误(它是生成错误的 getBoolean):

11-10 16:32:24.652: D/StrictMode(706): StrictMode policy violation; ~duration=229 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=2079 violation=2

结果是未读取该值,当我尝试使用此代码写入 SharedPreferences 时,我也得到相同的错误(它是生成错误的提交):

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("soundOn", soundOn);
editor.commit();

我能找到的这个错误的唯一答案是关于严格模式警告,但我的代码实际上无法读取/写入 SharedPreferences 键/值数据。

【问题讨论】:

标签: android


【解决方案1】:

您必须在单独的线程上执行文件系统操作,然后错误就会消失。

您也可以关闭 StrictMode(但我不建议这样做)

StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
    .permitDiskWrites()
    .build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);

【讨论】:

  • 好的,我现在在 Activity.onCreate 上创建一个线程,该线程在启动时读取属性并检查脏属性并在需要时写入这些属性,然后我在 Activity.onPause 上停止线程并重新启动它Activity.onResume。听起来对吗?
  • 它确实可以工作,并且我已经测试过当应用程序在后台时线程不活跃,所以它看起来不错。只是想听听你们巫师是否认为这听起来是个好方法;)
  • @Frank “doCorrectStuffThatWritesToDisk()”是什么意思?谢谢
  • 将内容写入磁盘的是您的“业务逻辑”。基本上我正在关闭严格模式,写入,重新打开严格模式。
【解决方案2】:

如果您在 Android 项目中配置了响应式 (RxJava),则可以利用其属性,例如在特定于 I/O 的调度程序上安排任务,例如:

public void saveFavorites(List<String> favorites) {
    Schedulers.io().createWorker().schedule(() -> {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favorites);
        editor.putString(Constants.FAVORITE, jsonFavorites);
        editor.apply();
    });
}

【讨论】:

  • 使用editor.commit() 避免浪费另一个线程,因为你已经在那里了。
猜你喜欢
  • 2018-09-25
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-09
相关资源
最近更新 更多