StrictModeDiskReadViolation时

Nei*_*ard 13 android

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

sharedPreferences = context.getSharedPreferences("MMPreferences", 0);
soundOn = sharedPreferences.getBoolean("soundOn", true);
Run Code Online (Sandbox Code Playgroud)

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

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

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

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("soundOn", soundOn);
editor.commit();
Run Code Online (Sandbox Code Playgroud)

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

Fra*_*ank 17

您必须在单独的线程上执行fileSystem操作,然后错误将消失.

你也可以关闭StrictMode(但我不推荐)

StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
    .permitDiskWrites()
    .build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);
Run Code Online (Sandbox Code Playgroud)

  • 它确实有效,而且我已经测试过当应用程序在后台时线程不活动,所以它看起来不错。只是想听听您的巫师是否认为这听起来是一个很好的方法;) (2认同)

yai*_*eno 5

如果您在 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();
    });
}
Run Code Online (Sandbox Code Playgroud)