我刚学会了SharedPreferences.Editor的apply()和commit()之间的区别。 apply()被认为是异步的,可以安全地在UI线程上运行; commit()被认为是同步的,不适合在UI线程上运行。所以我在MainActivity中使用点击监听器进行了一个简单的测试:
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("synced", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (int i = 0; i < 100000; ++i) {
editor.putString("index" + i, "index" + i);
}
Log.e("Test", System.nanoTime() + " SYNC ");
editor.commit();
Log.e("Test", System.nanoTime() + " SYNC " + sharedPreferences.getString("index99999", "NULL"));
SharedPreferences sharedPreferences2 = MainActivity.this.getSharedPreferences("asynced", 0);
SharedPreferences.Editor editor2 = sharedPreferences2.edit();
for (int i = 0; i < 100000; ++i) {
editor2.putString("index2" + i, "index2" + i);
}
Log.e("Test", System.nanoTime() + " ASYNC ");
editor2.apply();
Log.e("Test", System.nanoTime() + " ASYNC " + sharedPreferences2.getString("index299999", "NULL"));
我跑了好几次并得到了同样的结果:
05-25 01:11:44.608 16109-16109/darklord.preferencestest E/Test: 1295614410392 SYNC
05-25 01:11:44.667 16109-16109/darklord.preferencestest E/Test: 1295669350041 SYNC index99999
05-25 01:11:45.257 16109-16109/darklord.preferencestest E/Test: 1296262306521 ASYNC
05-25 01:11:45.317 16109-16109/darklord.preferencestest E/Test: 1296317374397 ASYNC NULL
我希望apply()必须加快commit(),但结果却是相同的。它们都不适合在ui线程上运行。那么为什么会这样呢?
编辑: 日志应该是
05-25 01:11:44.608 16109-16109/darklord.preferencestest E/Test: 1295614410392 SYNC
05-25 01:11:44.667 16109-16109/darklord.preferencestest E/Test: 1295669350041 SYNC index99999
05-25 01:11:45.257 16109-16109/darklord.preferencestest E/Test: 1296262306521 ASYNC
05-25 01:11:45.317 16109-16109/darklord.preferencestest E/Test: 1296317374397 ASYNC index249999
我正在模拟器api 17上进行测试。
答案 0 :(得分:4)
问题是你正在从内存中读回值
您之前创建的 SharedPreference
。
根据文件,
apply()将其更改提交到内存中的SharedPreferences 立即启动异步提交到磁盘
因此,内存中SharedPreference
将立即更新。