在Android系统中,经常使用SystemProperties去读写全局的属性值,通常这个属性值是存放在文件中的,在Linux层可以通过getprop和setprop去读写属性值。其实都是同一个东西。
在andorid框架中,SystemProperties来源于包android.os.SystemProperties;在framework中或者系统源码应用中可以随意使用。因为SystemProperties是一个隐藏类,所以在第三方应用中想使用SystemProperties通常使用反射。
一般来说实际开发中会写一个SystemProperties类,具体的get和set方法通过反射来实现。
public final class SystemProperties {
public static String get(String property, String defaultValue) {
try {
Class clazz = Class.forName("android.os.SystemProperties");
Method getter = clazz.getDeclaredMethod("get", String.class);
String value = (String) getter.invoke(null, property);
if (!TextUtils.isEmpty(value)) {
return value;
}
} catch (Exception e) {
Log.d("SystemProperties", "Unable to read system properties");
}
return defaultValue;
}
public static void set(String property, String value) {
try {
Class clazz = Class.forName("android.os.SystemProperties");
Method setter = clazz.getDeclaredMethod("set", String.class);
setter.invoke(null, property,value);
} catch (Exception e) {
Log.d("SystemProperties", "Unable to read system properties");
}
}
}
只需要调用SystemProperties.get()和SystemProperties.set()就可以了