安卓SystemProperties类在上层是不可见的
所以我们需要用系统属性来和系统程序以及executables可执行文件做交互的时候,上层app可以采用反射方式获取set/get方法:
/**
* Create by LankyBin on 2020-03-23
*/
public class PropSetter {
public void setProp(String key, String string) {
String value = string;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("set", String.class, String.class);
get.invoke(c, key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getProp(String key, String defaultValue) {
String value = defaultValue;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class, String.class);
value = (String) (get.invoke(c, key, "unknown"));
} catch (Exception e) {
e.printStackTrace();
} finally {
return value;
}
}
}
前段时间注意到,setprop时的key也就是属性名是有长度限制的,一般安卓默认限制是32个字符,这个需要注意一下,否则在反射调用的时候运行时会报异常。