SharedPreferences的使用

 

1.获取SharedPreferences

    1)通过上下文获取:

          Context.(file, mode);

         file:文件名,mode:文件类型,mode取值有Context.MODE_PRIVATE(私有,覆盖)、Context.MODE_APPEND(私有,追加)、Context.MODE_WORLD_READABLE(公开读,已经废弃)、Context.MODE_WORLD_WRITEABLE(公开读写,已经废弃)

          文件保存路径Context.getDataDir()/shared_prefs,文件名Context.getDataDir()/shared_prefs/file.xml

          修改某个Context的SharedPreferences的保存路径:

public static boolean setSharedPrefercencesSavaPath(Context context, String filePath) {
    try {
        // 获取ContextWrapper对象中的mBase变量。该变量保存了ContextImpl对象
        Field field = ContextWrapper.class.getDeclaredField("mBase");
        field.setAccessible(true);
        Object obj = field.get(context);
        // 获取ContextImpl。mPreferencesDir变量,该变量保存了数据文件的保存路径
        field = obj.getClass().getDeclaredField("mPreferencesDir");
        field.setAccessible(true);
        // 创建自定义路径
        File file = new File(filePath);
        // 修改mPreferencesDir变量的值
        field.set(obj, file);
        return true;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}

   2)直接构造:

         先看看Context是如何构造SharedPreferences的,源码在android.app.ContextImpl.java中。

//通过文件名获取 
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);
    }

//通过文件获取
 public SharedPreferences getSharedPreferences(File file, int mode) {
        SharedPreferencesImpl sp;
        synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                checkMode(mode);
                if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
                    if (isCredentialProtectedStorage()
                            && !getSystemService(UserManager.class)
                                    .isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
                        throw new IllegalStateException("SharedPreferences in credential encrypted "
                                + "storage are not available until after user is unlocked");
                    }
                }
                sp = new SharedPreferencesImpl(file, mode);//创造SharedPreferences
                cache.put(file, sp);
                return sp;
            }
        }
        if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
            getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
            // If somebody else (some other process) changed the prefs
            // file behind our back, we reload it.  This has been the
            // historical (if undocumented) behavior.
            sp.startReloadIfChangedUnexpectedly();
        }
        return sp;
    }


      通过源码发现,SharedPreferencesImpl是SharedPreferences实现,而且有一个构造方法是SharedPreferencesImpl(file, mode),file:文件,mode和1)中的mode一样,所以可以模仿Context创造,不过由于SharedPreferencesImpl是私有的所以比较麻烦,直接上代码

//获取SharedPreferences ,file保存的文件,mode文件类型(公有还是私有)
 public static SharedPreferences preferences(File file,int mode){
        try {
           Class cls = Class.forName("android.app.SharedPreferencesImpl");//获取SharedPreferencesImpl的Class
           Constructor<? extends SharedPreferences>constructor = cls.getDeclaredConstructor(File.class, int.class);//获取构造方法
            if (!constructor.isAccessible())
                constructor.setAccessible(true);
            return  constructor.newInstance(file,mode);//创建对象
        } catch (Exception e) {
            e.printStackTrace();
         return null;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值