Android : 反射机制获取或设置系统属性(SystemProperties)

来源:互联网 发布:南京软件开发平均工资 编辑:程序博客网 时间:2024/05/16 15:11

Android.os.SystemProperties 提供了获取和设置系统属性的方法,但是这个类被隐藏了,应用开发时无法直接访问,可以通过反射的机制进行操作。


获取系统属性

public static public String getProperty(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;      }}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

设置系统属性

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();    }  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

示例

  • 获取系统版本号(非Android版本)
getProperty("ro.build.display.id", "unknown");
  • 1
  • 1

通过 adb shell 打印系统属性的 key

  • 打开系统的命令行工具(开始中输入cmd)
  • 输入 adb shell 进入 adb shell
  • 输入 cd system 进入 system 目录
  • 输入 cat build.prop 查看所有系统属性

    cmd

  • 输入 cat build.prop | grep [指定字符串] 查看所有包含指定字符串的项

    cmd

0 0
原创粉丝点击