回忆Android中数据的存储方式有哪些,简单列举下。
1. SharedPreferences
Android
自带的数据存储,以xml
的形式存储在/data/data/packageName/shared_prefs
这里提一下提交的两种方式: commit
和 apply**
**
commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/**
* Commit your preferences changes back from this Editor to the
* {@link SharedPreferences} object it is editing. This atomically
* performs the requested modifications, replacing whatever is currently
* in the SharedPreferences.
*
*如果两个都在修改提交,那么以最后一个为主。也就是后面会覆盖前面的
* <p>Note that when two editors are modifying preferences at the same
* time, the last one to call commit wins.
*
* 如果你不关心返回结果在主线程中,考虑使用apply代替
* <p>If you don't care about the return value and you're
* using this from your application's main thread, consider
* using {@link #apply} instead.
*
* 返回true 表示成功
* @return Returns true if the new values were successfully written
* to persistent storage.
*/
boolean commit();apply
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35/**
*先立即提交到内存中,然后异步提交到数据库中
* <p>Unlike {@link #commit}, which writes its preferences out
* to persistent storage synchronously, {@link #apply}
* commits its changes to the in-memory
* {@link SharedPreferences} immediately but starts an
* asynchronous commit to disk and you won't be notified of
* any failures.
*
* 如果这个{@link SharedPreferences}上的editor执行常规的{@link #commit},而 *{@link #apply}仍然未完成,那么{@link #commit}将阻塞,直到所有异步提交以及提交本身都 * 完成。
* If another editor on this
* {@link SharedPreferences} does a regular {@link #commit}
* while a {@link #apply} is still outstanding, the
* {@link #commit} will block until all async commits are
* completed as well as the commit itself.
*
* sharedPreferences在一个进程中是单例的,它是安全的apply ,如果你不需要返回值的话
* <p>As {@link SharedPreferences} instances are singletons within
* a process, it's safe to replace any instance of {@link #commit} with
* {@link #apply} if you were already ignoring the return value.
*
* 不需要担心Android的生命周期,它会确保写入硬盘中再切换状态
* <p>You don't need to worry about Android component
* lifecycles and their interaction with <code>apply()</code>
* writing to disk. The framework makes sure in-flight disk
* writes from <code>apply()</code> complete before switching
* states.
*
* <p class='note'>The SharedPreferences.Editor interface
* isn't expected to be implemented directly. However, if you
* previously did implement it and are now getting errors
* about missing <code>apply()</code>, you can simply call
* {@link #commit} from <code>apply()</code>.
*/
void apply();
结论
- 在不考虑跨进程通信和返回值的情况下,可以优先选择
apply
,可以快速读取更新后的值。