StrictModeDiskReadViolation时StrictModeDiskReadViolation

2023-09-06 11:31:25 作者:狂奔的、蜗牛

林新Android开发人员,我想使用共享preferences存储一些用户设置为我的应用程序。我有这个code在我Activity.onCreate方式:

Im new to Android dev, and I am trying to use SharedPreferences to store some user settings for my app. I have this code in my Activity.onCreate method:

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

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

but it gives me this error (it is the getBoolean that generates the error):

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

和结果是该值不读,我也得到了同样的错误,当我尝试写的共享preferences与此code(它是在提交生成错误):

and the result is that the value is not read and I also get the same error when I try to write to the SharedPreferences with this code (it is the commit that generates the error):

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

有关这个错误我能找到的唯一答案是关于严格模式的警告,但是我的code实际上无法读取/写入共享preferences键/值数据。知道为什么吗?

The only answers for this error I can find is about a strict mode warning, but my code actually fails to read/write the SharedPreferences key/value data. Any idea why?

感谢您 瑟伦

推荐答案

您必须执行文件系统操作上的一个单独的线程,则错误会自行消失。

You must do fileSystem operations on a separate thread, then the error will go away.

您也可以关闭StrictMode(但我没有,建议)

you can also turn off the StrictMode (but i am not recommending that)

StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
    .permitDiskWrites()
    .build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);
相关推荐