StrictMode DiskReadViolation 时

2024-03-31

我正在尝试使用 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

StrictMode DiskReadViolation 时 的相关文章

随机推荐