1.定义属性的操作类
//获取属性
static String getProperty(String key, String defaultValue) {
String value = defaultValue;
try {
//获取对应的属性类 SystemProperties
Class<?> c = Class.forName("android.os.SystemProperties");
//得到具体的方法,第一个参数 表示要查找的方法名 后面的参数指定对应的形参类型
Method get = c.getMethod("get", String.class, String.class);
//Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,返回值也是对象
//invoke 就是调用对应类的对应方法 第一个参数是要调用的方法所隶属的对象实体 第二个参数是方法的参数值
value = (String) get.invoke(c, key, "unknown" );
} catch (Exception e) {
e.printStackTrace();
}
finally {
return value;
}
}
//设置属性
public static void setProperty(String key, String value) {
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method set = c.getMethod("set", String.class, String.class);
set.invoke(c, key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
2.调用获取属性
String property = getProperty("ro.oem.key1", "unknown");
try {
Class secure = Class.forName("android.provider.Settings$Secure");
Method method = secure.getDeclaredMethod("putInt",android.content.ContentResolver.class,java.lang.String.class,int.class);
method.invoke(null,getContentResolver(),SHOW_IME_WITH_HARD_KEYBOARD,isChecked ? 1 : 0);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
内部类使用 $ 连接外部类和内部类
getDeclaredMethod需要指定方法的参数,如果不指定参数类型,默认查找没有参数的方法,有可能会找不到方法,int 这种基本数据类型 使用int.class 其他类使用全类名
invoke 方法需要传入参数,第一个参数是方法的拥有者,一般传null即可,后面传的是方法的参数