Usp,SharedPreferences的封装 - lyloou/lou GitHub Wiki

Usp,SharedPreferences的封装

简介

工具类Usp是对数据存储类SharedPreferences的封装;

用法

初始化

在自定义的Application的onCreate()重写方法中进行初始化

@Override
public void onCreate() {
	super.onCreate();
	Usp.init(this);
}

保存值

Usp.getInstance()
		.putInt(KEY_ARG1, arg1 + 1)
		.putInt(KEY_ARG2, arg2 - 1)
		.apply();

获取值

int arg1 = Usp.getInstance().getInt(KEY_ARG1, 0);
int arg2 = Usp.getInstance().getInt(KEY_ARG2, 0);

小技巧:快速输入常量key

利用Android Studio在类成员域里通过输入key,然后按下「TAB」按键,可以快速输入常量key

private static final String KEY_ARG1 = "ARG1";

apply和commit的区别

apply() was added in 2.3, it commits without returning a boolean indicating success or failure. commit() returns true if the save works, false otherwise. apply() was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.

源码链接