我正在尝试使用 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 键/值数据。
最佳答案
您必须在单独的线程上执行文件系统操作,然后错误就会消失。
你也可以关闭 StrictMode(但我不建议这样做)
StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
.permitDiskWrites()
.build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);
关于android - StrictModeDiskReadViolation 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323431/