如果您使用 apply,在单独的线程中编辑共享首选项是否多余?
我的 MainActivity 的 onCreate 方法中有以下代码块:
final MainActivity activityReference = this;
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
// if it is the first time running
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activityReference);
if(!prefs.getBoolean(MainActivity.FIRST_LOAD, false)) {
// enable a setting on first run
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(MainActivity.FIRST_LOAD, true);
editor.apply();
}
}
});
因为 SharedPreferences.Editor 的实例正在调用 apply 方法,所以它应该是异步的,但在单独的线程中运行之前,我们仍然会违反严格模式。违规是 StrictModeDiskRead 违规,因此假设它们是由于获取 SharedPreferences 而不是调用 apply。此外,三星设备似乎几乎完全有这个问题。
最佳答案
Is editing shared preferences in a separate thread redundant if you use apply?
是的,但请记住,您可能不会仅在编辑 SharedPreferences
。您可能也在阅读它们。
鉴于您的代码的性质,我猜您将其称为 LAUNCHER
Activity 中的第一件事。如果是这样,那么其他任何东西都不会检索到那些 SharedPreferences
,因此您将在读取时从 StrictMode
获得磁盘读取违规,而不是编辑。
既然你已经有了后台线程,我会切换到 commit()
而不是使用 apply()
并浪费另一个线程。
关于android - 在单独的线程上访问 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25167952/