Android修改默认SharedPreferences文件的路径,SharedPreferences常用工具类
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);
} }
转自:http://www.cnblogs.com/Westfalen/p/5380737.html
Android修改默认SharedPreferences文件的路径,SharedPreferences常用工具类的更多相关文章
- Android 常用工具类之SPUtil,可以修改默认sp文件的路径
参考: 1. 利用Java反射机制改变SharedPreferences存储路径 Singleton1900 2. Android快速开发系列 10个常用工具类 Hongyang import ...
- vue项目工具文件utils.js javascript常用工具类,javascript常用工具类,util.js
vue项目工具文件utils.js :https://blog.csdn.net/Ajaxguan/article/details/79924249 javascript常用工具类,util.js : ...
- VS2015如何另存解决方案文件-修改解决方案sln文件的路径
原文:VS2005如何另存解决方案文件-修改解决方案sln文件的路径 修改解决方案sln文件的路径 方法一:工具→选项→项目和解决方案,可设置项目的默认保存位置.方法二:"解决方案资源管理器 ...
- Android快捷便利但不常被使用的原生工具类
Android快捷便利但不常被使用的原生工具类 Android SDK原生 API中,有一些常用的工具类,运用得当可以省事省力省时,何况还是Android官方提供的,现在收集整理一些出来.DateUt ...
- [C#] 常用工具类——文件操作类
/// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- 文件压缩、解压工具类。文件压缩格式为zip
package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...
- 我的Android进阶之旅------>Android关于dp(dip)、sp转px的工具类
下面是一个工具类,提供了dp.sp.px之间相互转化的方法. import android.content.Context; /** * dp.sp 转换为 px 的工具类<br> * & ...
- Laravel 修改默认日志文件名称和位置
修改默认日志位置 我们平常的开发中可能一直把laravel的日志文件放在默认位置不会有什么影响,但如果我们的项目上线时是全量部署,每次部署都是git中最新的代码,那这个时候每次都会清空我们的日志,显示 ...
随机推荐
- 连表查询都用Left Join吧 以Windows服务方式运行.NET Core程序 HTTP和HTTPS的区别 ASP.NET SignalR介绍 asp.net—WebApi跨域 asp.net—自定义轻量级ORM C#之23中设计模式
连表查询都用Left Join吧 最近看同事的代码,SQL连表查询的时候很多时候用的是Inner Join,而我觉得对我们的业务而言,99.9%都应该使用Left Join(还有0.1%我不知道在 ...
- Java调用Linux命令(cd的处理)
一.Java调用Linux系统的命令非常简单 这是一个非常常用的调用方法示例: public String executeLinuxCmd(String cmd) { System.out.print ...
- C#实现相似QQ的隐藏浮动窗口、消息闪动
功能简单介绍 当语音客服系统登录成功进入主界面时,本聊天工具将会自己主动隐藏在左下角位置,当鼠标移动到左下角时,自己主动弹出,当鼠标移开聊天窗口时,自己主动隐藏.假设想让聊天窗口固定在桌面.仅仅要拖动 ...
- JAVA class 编译jar。 控制台使用jar
//编译jar jar -cvf -mgtvEncode.jar -mgtvEncode.class //使用jar java -cp mgtvEncode.jar mgtvEncode
- linux yum源安装
#1.安装remi源mkdir /disk1/toolscd /disk1/toolsrpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-relea ...
- 简易C#动态加载dll(实现插件化)
可以通过该方法来实现程序插件化. 假设A,B两个类,A类为宿主,B类为插件需要加载到A类中: class Program { public interface IHellow { void Hello ...
- [k8s]prometheus+grafana监控node和mysql(普罗/grafana均vm安装)
https://github.com/prometheus/prometheus Architecture overview Prometheus Server Prometheus Server 负 ...
- 【Android】17.4 Activity与IntentService的绑定
分类:C#.Android.VS2015: 创建日期:2016-03-03 一.简介 本示例通过AlarmManager类以固定的时间间隔调用服务(每隔2秒更新一次随机生成的股票数据).如果将此示例的 ...
- C#中的 .NET 弱事件模式
引言 你可能知道,事件处理是内存泄漏的一个常见来源,它由不再使用的对象存留产生,你也许认为它们应该已经被回收了,但不是,并有充分的理由. 在这个短文中(期望如此),我会在 .Net 框架的上下文事件处 ...
- centos7 nginx安装 及MySQL-python
1.pip install MySQL-python 出错问题 pip install -r requirement.txt 发现安装MySQL-python 出错,更新setuptools也没用 解 ...