Android修改SharePreference路径

ContextImpl里面有一个字段mPreferencesDir,这个文件目录就是保存了SharePreference路径的,只需要修改这个为我们自定义的路径就好了,由于ContextImpl是一个隐藏类,我们需要使用反射去实现,下面是具体的代码:

try {
            Class<?> clazz=Class.forName("android.app.ContextImpl");
            Method method=clazz.getDeclaredMethod("getImpl", Context.class);
            method.setAccessible(true);
            Object mContextImpl=method.invoke(null,this);
            //获取ContextImpl的实例
            Log.d("csdn","mContextImpl="+mContextImpl);
            Field mPreferencesDir=clazz.getDeclaredField("mPreferencesDir");
            mPreferencesDir.setAccessible(true);
            //自定义路径
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File file=new File(Environment.getExternalStorageDirectory(),"new_shared_pres");
                if (!file.exists()){
                    file.mkdirs();
                }
                mPreferencesDir.set(mContextImpl,file);
                Log.d("csdn","修改sp路径成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

猜你喜欢

转载自blog.csdn.net/QQsongQQ/article/details/81735259