通过反射来读写build.prop参数
build.prop里面有很多关于手机参数的相关配置信息,其对应的参数读写是在android.os.SystemProperties.java这个类中完成。除非我们的应用有系统签名,不然的话不能直接调用里面的方法。但是通过java的反射我们就可以很容易的去调用。
我们先来看一下SystemProperties.java这个类的两个关键的方法get和set:
/**
* Get the value for the given key.
* @return an empty string if the key isn't found
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(String key) {
if (key.length() > PROP_NAME_MAX) {
throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
}
return native_get(key);
}
/**
* Set the value for the given key.
* @throws IllegalArgumentException if the key exceeds 32 characters
* @throws IllegalArgumentException if the value exceeds 92 characters
*/
public static void set(String key, String val) {
if (key.length() > PROP_NAME_MAX) {
throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
}
if (val != null && val.length() > PROP_VALUE_MAX) {
throw new IllegalArgumentException("val.length > " +
PROP_VALUE_MAX);
}
native_set(key, val);
}
get方法传入一个键,然后就可以获取这个键对应的值(在adb shell里面我们可以通过getprop命令来查看所有的键以及对应的值)。
set方法参数是对应的键和值。
根据这些信息,我们可以很容易来通过反射来读写:
// 读
private String getValueFromProp() {
String value = "";
Class<?> classType = null;
try {
classType = Class.forName("android.os.SystemProperties");
//拿到get方法,此方法传入一个String类型参数。
Method getMethod = classType.getDeclaredMethod("get", new Class<?>[]{String.class});
// 键值persist.sys.sb.hide,其他的也可以。
value = (String) getMethod.invoke(classType, new Object[]{"persist.sys.sb.hide"});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return value;
}
// 写
private void setValueToProp() {
Class<?> classType = null;
try {
classType = Class.forName("android.os.SystemProperties");
//拿到set方法,此方法传入两个String类型参数,一个是键,一个是设定的值。
Method getMethod = classType.getDeclaredMethod("set", new Class[]{String.class, String.class});
// 对persist.sys.sb.hide这一项设定值为1。
getMethod.invoke(classType, new String[]{"persist.sys.sb.hide", "1"});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}