参考:

1.  利用Java反射机制改变SharedPreferences存储路径    Singleton1900

2.  Android快速开发系列 10个常用工具类       Hongyang

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences; import com.imageviewpager.language.MyApplication; import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map; public class SPUtil { /** debug 环境下允许修改 sp文件的路径 */
public static final boolean isDebug = true;
/** 修改以后的sp文件的路径 MyApplication.getContext().getExternalFilesDir(null).getAbsolutePath()=/sdcard/Android/%package_name%/file */
public static final String FILE_PATH = MyApplication.getContext().getExternalFilesDir(null).getAbsolutePath(); /**
* 保存数据
*
* @param context
* @param fileName 文件名, 不需要".xml"
* @param keyName
* @param value
*/
public static void put(Context context, String fileName, String keyName, Object value) {
SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
if (value instanceof String) {
editor.putString(keyName, (String) value);
} else if (value instanceof Integer) {
editor.putInt(keyName, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(keyName, (Boolean) value);
} else if (value instanceof Float) {
editor.putFloat(keyName, (Float) value);
} else if (value instanceof Long) {
editor.putLong(keyName, (Long) value);
} else {
editor.putString(keyName, value.toString());
} SharedPreferencesCompat.apply(editor);
} /**
* 获取数据
*
* @param context
* @param fileName
* @param keyName
* @param defaultValue 默认值
* @return
*/
public static Object get(Context context, String fileName, String keyName, Object defaultValue) {
SharedPreferences sp = getSharedPreferences(context, fileName);
if (defaultValue instanceof String) {
return sp.getString(keyName, (String) defaultValue);
} else if (defaultValue instanceof Integer) {
return sp.getInt(keyName, (Integer) defaultValue);
} else if (defaultValue instanceof Boolean) {
return sp.getBoolean(keyName, (Boolean) defaultValue);
} else if (defaultValue instanceof Float) {
return sp.getFloat(keyName, (Float) defaultValue);
} else if (defaultValue instanceof Long) {
return sp.getLong(keyName, (Long) defaultValue);
}
return null;
} /**
* 移除某个key值对应的值
*
* @param context
* @param fileName
* @param keyName
*/
public static void remove(Context context, String fileName, String keyName) {
SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
editor.remove(keyName);
SharedPreferencesCompat.apply(editor);
} /** 清除所有数据 */
public static void clear(Context context, String fileName) {
SharedPreferences.Editor editor = getSharedPreferences(context, fileName).edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
} /**
* 查询某个key是否已经存在
*
* @param context
* @param keyName
* @return
*/
public static boolean contains(Context context, String fileName, String keyName) {
return getSharedPreferences(context, fileName).contains(keyName);
} /** 返回所有的键值对 */
public static Map<String, ?> getAll(Context context, String fileName) {
return getSharedPreferences(context, fileName).getAll();
} /** 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 */
private static class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod(); /** 反射查找apply的方法 */
@SuppressWarnings({"unchecked", "rawtypes"})
private static Method findApplyMethod() {
try {
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e) {
} return null;
} /** 如果找到则使用apply执行,否则使用commit */
public static void apply(SharedPreferences.Editor editor) {
try {
if (sApplyMethod != null) {
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
editor.commit();
}
} /**
* @param context
* @param fileName
* @return isDebug = 返回修改路径(路径不存在会自动创建)以后的 SharedPreferences :%FILE_PATH%/%fileName%.xml<br/>
* !isDebug = 返回默认路径下的 SharedPreferences : /data/data/%package_name%/shared_prefs/%fileName%.xml
*/
private static SharedPreferences getSharedPreferences(Context context, String fileName) {
if (isDebug) {
try {
// 获取ContextWrapper对象中的mBase变量。该变量保存了ContextImpl对象
Field field = ContextWrapper.class.getDeclaredField("mBase");
field.setAccessible(true);
// 获取mBase变量
Object obj = field.get(context);
// 获取ContextImpl。mPreferencesDir变量,该变量保存了数据文件的保存路径
field = obj.getClass().getDeclaredField("mPreferencesDir");
field.setAccessible(true);
// 创建自定义路径
File file = new File(FILE_PATH);
// 修改mPreferencesDir变量的值
field.set(obj, file);
// 返回修改路径以后的 SharedPreferences :%FILE_PATH%/%fileName%.xml
return context.getSharedPreferences(fileName, Activity.MODE_PRIVATE);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// 返回默认路径下的 SharedPreferences : /data/data/%package_name%/shared_prefs/%fileName%.xml
return context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
} }

Android 常用工具类之SPUtil,可以修改默认sp文件的路径的更多相关文章

  1. Android修改默认SharedPreferences文件的路径,SharedPreferences常用工具类

    import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; ...

  2. 53. Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...

  3. 【转】Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefe ...

  4. android常用工具类

    import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkIn ...

  5. Android 常用工具类之 ScreenUtil

    需求: 截屏 参考 :    Android开发:截屏 screenshot 功能小结 package bvb.de.openadbwireless.utils; import android.app ...

  6. eclipse工具类及插件(修改eclipse.ini文件及作者名字)

    https://jingyan.baidu.com/album/9158e0005633c0a254122807.html?picindex=1 (修改eclipse.ini文件及作者名字) http ...

  7. Android 常用工具类之LogUtil,可以定位到代码行,双击跳转

    package cn.utils; import android.util.Log; public class LogUtils { public static boolean isDebug = t ...

  8. Android常用工具类封装---SharedPreferencesUtil

    SharedPreferences常用于保存一些简单的数据,如记录用户操作的配置等,使用简单. public class SharedPreferencesUtil {              // ...

  9. Android 常用工具类之 DimenUtil

    public class DimenUtil { /** sp转换成px */ public static int sp2px(float spValue) { float fontScale = M ...

随机推荐

  1. uwsgi选择使用的python版本(转载)

    大概如下 mkdir /data/uwsgi cd /data/uwsgi wget http://projects.unbit.it/downloads/uwsgi-2.0.11.tar.gz ta ...

  2. 打补丁patch 命令使用

    打补丁patch 命令使用 http://www.cnblogs.com/huanghuang/archive/2011/07/14/2106402.html patch 命令用于打补丁,补丁文件是使 ...

  3. 使用 tox flake8 pytest 规范 python 项目

    使用 tox flake8 pytest 规范 python 项目 python 中有些很好的工作来规范整个项目的开发,而其中使用较多的就是使用 tox . flake8 . pytest . tox ...

  4. SQL Server Transaction Log Truncate && Shrink

    目录 什么是事务日志 事务日志的组成 事务日志大小维护方法 Truncate Shrink 索引碎片 总结 什么是事务日志 Transaction log   是对数据库管理系统执行的一系列动作的记录 ...

  5. 一个前端html模板处理引擎(javascript) - pure

    做后台开发(java/python)的同学开发web应用,对于前端页面生成技术并不陌生,像jsp,freemark等.开发UGC类型的互联网站,因为要SEO友好,所以一般都会在后台用模板引擎直接生成好 ...

  6. Visual Studio 2015 + IIS Express 10.0 调试 ASP.NET 项目

    参考资料: https://msdn.microsoft.com/zh-cn/library/58wxa9w5(v=vs.120).aspx 首先搭建环境, 也就是用 IIS Express 配置一个 ...

  7. Git 使用的配置 常用命令

    老文一篇 搬过来 1. git的部分配置 # 全局提交用户名与邮箱 git config --global user.name "simon" git config --globa ...

  8. leetcode-5 最长回文子串(动态规划)

    题目要求: * 给定字符串,求解最长回文子串 * 字符串最长为1000 * 存在独一无二的最长回文字符串 求解思路: * 回文字符串的子串也是回文,比如P[i,j](表示以i开始以j结束的子串)是回文 ...

  9. Swift语言实战晋级-第9章 游戏实战-跑酷熊猫-2 创建熊猫类

    当我们创建好项目文件后我们就可以开始一步一步的按照我们之前列入的清单来编写我们的游戏.现在就让我们来创建一个熊猫这个类Panda.swift.我们将采取分解的方式,一步一步的完成Panda.swift ...

  10. Lintcode: Matrix Zigzag Traversal

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-or ...