Android 常用工具类之SPUtil,可以修改默认sp文件的路径
参考:
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文件的路径的更多相关文章
- Android修改默认SharedPreferences文件的路径,SharedPreferences常用工具类
import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; ...
- 53. Android常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...
- 【转】Android常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefe ...
- android常用工具类
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkIn ...
- Android 常用工具类之 ScreenUtil
需求: 截屏 参考 : Android开发:截屏 screenshot 功能小结 package bvb.de.openadbwireless.utils; import android.app ...
- eclipse工具类及插件(修改eclipse.ini文件及作者名字)
https://jingyan.baidu.com/album/9158e0005633c0a254122807.html?picindex=1 (修改eclipse.ini文件及作者名字) http ...
- Android 常用工具类之LogUtil,可以定位到代码行,双击跳转
package cn.utils; import android.util.Log; public class LogUtils { public static boolean isDebug = t ...
- Android常用工具类封装---SharedPreferencesUtil
SharedPreferences常用于保存一些简单的数据,如记录用户操作的配置等,使用简单. public class SharedPreferencesUtil { // ...
- Android 常用工具类之 DimenUtil
public class DimenUtil { /** sp转换成px */ public static int sp2px(float spValue) { float fontScale = M ...
随机推荐
- POJ1326问题描述
Description Mileage program of ACM (Airline of Charming Merlion) is really nice for the travelers fl ...
- 详解OpenGL中的各种变换(投影变换,模型变换,视图变换)(完)——法线变换
前面两节内容已经说完了所有的三种变换.也就是说我们现在程序里面既不需要glLookAt(),也不需要gluPerspective(),这些矩阵我们都可以自己写.然后,再用glMultMatrix()来 ...
- 使用 tox flake8 pytest 规范 python 项目
使用 tox flake8 pytest 规范 python 项目 python 中有些很好的工作来规范整个项目的开发,而其中使用较多的就是使用 tox . flake8 . pytest . tox ...
- C#高级编程 反射 代码示例
反射 反射(Reflection)是.NET中的重要机制,通过反射,可以在运行时获得.NET中每一个类型(包括类.结构.委托.接口和枚举等)的成员,包括方法.属性.事件,以及构造函数等. 还可以获得每 ...
- Java基础——数组Array
一.数组基本概念 数组是相同类型数据的有序集合. 数组描述的是相同类型的若干个数据,按照一定的先后次序排列组合而成.其中,每一个数据称作一个数组元素,每个数组元素可以通过一个下标来访问它们. 数组有三 ...
- Spring Boot flyway的启动时机比较早
flyway,如果已经创建的版本V1中已经更新,则会validation报错 at org.springframework.boot.devtools.restart.RestartLauncher. ...
- nodejs weixin 笔记
http://www.oschina.net/code/snippet_218887_25870 好文章: http://codelife.me/blog/2013/04/23/developing- ...
- Ajax.ActionLink()方法的使用
第一句话都会这么去写:程序猿就是苦逼,除了开发还要会写博文!哎,今天就和大家一起讨论下Ajax的辅助方法ActionLink的使用,如果有讲的不好的地方或错的地方,请大家务必扔板砖,要投准哦,砸死我算 ...
- Java socket中关闭IO流后,发生什么事?(以关闭输出流为例)
声明:该博文以socket中,关闭输出流为例进行说明. 为了方便讲解,我们把DataOutputstream dout = new DataOutputStream(new BufferedOutpu ...
- 寻找第K大的数
在一堆数据中查找到第k个大的值. 名称是:设计一组N个数,确定其中第k个最大值,这是一个选择问题,解决这个问题的方法很多. 所谓“第(前)k大数问题”指的是在长度为n(n>=k)的乱序数组中S找 ...