您的位置:首页 > 移动开发 > Android开发

Android SharedPreferences理解

2016-04-05 00:00 507 查看
摘要: SharedPreferences

SharedPreferences是单例对象

只在第一次调用getSharedPreferences方法时打开文件时,创建一个实例对象。并放入map中,第二次获取数据从map 中获取,不需再解析。

写操作有两步,一是把数据先写入内存中,即map集合,二是把数据写入硬盘文件中。

SharedPreferences.Editor是用来修改SharedPreferences对象值的接口。你在editor 做出的修改都是待处理的,并没有被复制到SharedPreferences里,直到你调用commit()或apply()修改才会被执行。

commit():线程安全,性能慢,一般来说在当前线程完成写文件操作apply():线程不安全,性能高,异步处理IO操作,一定会把这个写文件操作放入一个SingleThreadExecutor线程池中处理不过apply()方法有个坑,那就是如果在一个Activity调用过多的apply()方法,在Activity关闭时,系统会等待所有放到内存map的都写完磁盘,才关闭Activity。所以一个Activity如果频繁操作SP,最好放到线程中,使用commit提交

ActivityThread.java


private void handleStopActivity(IBinder token, boolean show, int configChanges) {
.....................
// Make sure any pending writes are now committed.
if (!r.isPreHoneycomb()) {
QueuedWork.waitToFinish();
}
.....................
}


/**
* Internal utility class to keep track of process-global work that's
* outstanding and hasn't been finished yet.
*
* This was created for writing SharedPreference edits out
* asynchronously so we'd have a mechanism to wait for the writes in
* Activity.onPause and similar places, but we may use this mechanism
* for other things in the future.
*
* @hide
*/
public class QueuedWork {


/**
* Finishes or waits for async operations to complete.
* (e.g. SharedPreferences$Editor#startCommit writes)
*
* Is called from the Activity base class's onPause(), after
* BroadcastReceiver's onReceive, after Service command handling,
* etc.  (so async work is never lost)
*/
public static void waitToFinish() {
Runnable toFinish;
while ((toFinish = sPendingWorkFinishers.poll()) != null) {
toFinish.run();
}
}


clear清除数据,必须要commit或apply
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SharedPreferences