SharedPreferences原理解析

SharedPreferences是Android中用于轻量级数据存储的Key-Value存储方式,它通过文件系统进行持久化,并且在内存中缓存数据。本文详细介绍了SharedPreferences的使用、获取过程、数据存储(包括commit和apply的区别)、线程安全性以及跨进程问题,并探讨了其在面试中的常见问题和替代方案。了解这些可以帮助优化存储操作,避免引发ANR等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SharedPreferences介绍

SharedPreferences是Android官方的Key-Value键值对形式的轻量级存储方式,能够存储少量的数据,支持基本类型、字符串类型。

文件存储路径是/data/data/应用程序包名/shared_prefs

SharedPreferences使用

1、创建SharedPreferences

SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode);

参数1:SharedPreferences文件名称。

参数2:

Context.MODE_PRIVATE:表示数据只能被本应用程序读、写。
Context.MODE_WORLD_READABLE:表示数据能被其他应用程序读,但不能写。
Context.MODE_WORLD_WRITEABLE: 表示数据能被其他应用程序读,写。
Context.MODE_MULTI_PROCESS:跨进程。

2、使用Editor

// 创建SP对象
SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
// 创建Editor对象
SharedPreferences.Editor edit = sp.edit();
// 使用Editor存储数据
edit.putInt(key, value);
// 使用Editor同步提交数据
edit.commit();

SharedPreferences.Editor的方法:

 public interface Editor {
   
   
     // 存储数据
     Editor putString(String key, @Nullable String value);
     Editor putStringSet(String key, @Nullable Set<String> values);
     Editor putInt(String key, int value);
     Editor putLong(String key, long value);
     Editor putFloat(String key, float value);
     Editor putBoolean(String key, boolean value);
     
     // 删除SharedPreferences中指定key对应的数据项 
     Editor remove(String key);
     // 清空SharedPreferences里所有数据 
     Editor clear();
     // 当Editor编辑完成后,使用该方法同步提交修改
     boolean commit();
     // 当Editor编辑完成后,使用该方法异步提交修改
     void apply();
}

getSharedPreferences过程

使用SharedPreferences的时候是从上下文context.getSharedPreferences获取的,所以直接从Context类中找到该接口:

public abstract SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode);

发现只是抽象接口,所以再从实现类ContextImpl中找到该方法的实现:

getSharedPreferences(String name, int mode)方法

@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
   
   
    if (mPackageInfo.getApplicationInfo().targetSdkVersion <
        Build.VERSION_CODES.KITKAT) {
   
   
        if (name == null) {
   
   
            name = "null";
        }
    }
    File file;
    // 添加同步锁
    synchronized (ContextImpl.class) {
   
   
        if (mSharedPrefsPaths == null) {
   
   
            // 创建Map存储sp的文件
            mSharedPrefsPaths = new ArrayMap<>();
        }
        file = mSharedPrefsPaths.get(name);
        if (file == null) {
   
   
            // 获取sp的存储文件
            file = getSharedPreferencesPath(name);
            // 缓存到map中
            mSharedPrefsPaths.put(name, file);
        }
    }
    return getSharedPreferences(file, mode);
}

getSharedPreferencess(File file, int mode)方法

@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
   
   
    SharedPreferencesImpl sp;
    //添加同步锁
    synchronized (ContextImpl.class) {
   
   
        final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
        //从缓存中获取SharedPreferencesImpl对象
        sp = cache.get(file);
        if (sp == null) {
   
   
            checkMode(mode);  
            // 如果不存在则创建SharedPreferencesImpl对象
            sp = new SharedPreferencesImpl(file, mode);
            cache.put(file, sp);
            return sp;
        }
    }
    //  提供了 MODE_MULTI_PROCESS 这个 Flag 来支持跨进程
    if ((mode & Context.MODE_MULTI_PROCESS) != 0 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ruiurrui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值