SharedPreferences

2021-06-30  本文已影响0人  12313凯皇

前言

SharePreference简称SP,是Android中一种简易的轻量级存储方式。SP采用key-value(键值对)形式来存储数据,最终以xml格式的文件来持久化到存储介质上。默认的存储位置在data/data/<包名>/shared_prefs目录下,当用户卸载此应用数据时,SP保存的数据会一并清除。

使用场景

简单使用

//获取sp对象,传入int类型mode
val sp = getSharedPreferences("test",Context.MODE_PRIVATE)
val editor = sp.edit() 
editor.putString("name", "12313kaihuang")
//commit writes its data to persistent storage immediately, whereas apply will handle it in the background
editor.apply() 

val name: String? = sp.getString("name", null)
Log.d(TAG, "initButton: name = $name")

获取sp对象有两种方式,一种是通过ComtextImpl.getPreferences方法,第二种是通过PreferenceManager.getDefaultSharedPreferences(context),不过目前(API 30)已经过时了。

get方法可传入的mode:

源码分析

时间关系先记录后面再加注释

getShareperence

public SharedPreferences getSharedPreferences(String name, int mode) {
        // At least one application in the world actually passes in a null
        // name.  This happened to work because when we generated the file name
        // we would stringify it to "null.xml".  Nice.
        if (mPackageInfo.getApplicationInfo().targetSdkVersion <
                Build.VERSION_CODES.KITKAT) {
            if (name == null) {
                name = "null";
            }
        }

        File file;
        synchronized (ContextImpl.class) {
            if (mSharedPrefsPaths == null) {
                mSharedPrefsPaths = new ArrayMap<>();
            }
            file = mSharedPrefsPaths.get(name);
            if (file == null) {
                file = getSharedPreferencesPath(name);
                mSharedPrefsPaths.put(name, file);
            }
        }
        return getSharedPreferences(file, mode);
    }

总结

commit()和apply()的区别

Sharedpreferences保存数据量不易过大
否则会带来几个问题:

参考文章

上一篇下一篇

猜你喜欢

热点阅读