android 持久化-SharedPreferences

2018-01-29  本文已影响15人  风___________

1. 简单使用

// 获取 SharedPreferences 实例对象
SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(context);
// 存
SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(MOBLIE_CACHE_KEY,mobileString);
        editor.apply();
        // 或者用
        // editor.commit();

// 取
sharedPreferences.getString(MOBLIE_CACHE_KEY,"");

2. 简单的封装

  1. 使用:
SharedPreferences sharedPreferences = KapSharePreferenceManager.getSharedPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(MOBLIE_CACHE_KEY,mobileString);
editor.apply();
  1. 实现:
public class KapApplication extends Application{
    private static KapApplication instance;
    public static KapApplication getInstance() {
        return instance;
    }
    private static Context context;
    private static KapUserAccount userAccount = null;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        instance = this;
 }
...
public class KapSharePreferenceManager {
    private static SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(KapApplication.getContext());
    public static SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }
}

3. apply()和commit()方法异同

上一篇 下一篇

猜你喜欢

热点阅读