android - StrictModeDiskReadViolation 时

标签 android

我正在尝试使用 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/

相关文章:

android - InAPPBilling中IABHelper和IInAppBillingService的区别

android - Cordova + Android Studio 报错:'com.android.build.gradle.BasePlugin' 没有实现Plugin接口(interface)

java - 使用 DOM Android 从 Xml 读取 UTF8 和 Cp1256

android - Jetpack 撰写仅粗体字符串占位符

java - Android 中使用 DataAdapter 在 GridView 中显示数据

java - 光标不刷新,直到我在 android 中重新启动设备

android - 如何在 Android Google Maps API 上平滑折线方向?

android - Kotlin 适用于 String 未按预期工作

Android 2.3 和 Adhoc

java - 如何在Java(Eclipse,android)中使用printstacktrace?