[关闭]
@act262 2017-01-24T02:36:49.000000Z 字数 1888 阅读 2930

SystemProperties系统属性使用

Android_Framework


SystemProperties是系统内部的类,标记为@hide,所以一般情况下是不能直接用的,
像开发者选项里面的属性就是通过这个来读写的,其中key大多是以debug.作为前缀的.

可以通过反射方式调用,其中的set/get属性方法来达到修改的目的,也可以在adb shell中读写

  1. adb shell getprop debug.layout
  2. adb shell setprop debug.layout true
  1. private static Class<?> clz() {
  2. try {
  3. return Class.forName("android.os.SystemProperties");
  4. } catch (ClassNotFoundException e) {
  5. e.printStackTrace();
  6. }
  7. return null;
  8. }
  9. public static void set(String key, String val) {
  10. try {
  11. Method method = clz().getMethod("set", String.class, String.class);
  12. method.invoke(null, key, val);
  13. } catch (NoSuchMethodException e) {
  14. e.printStackTrace();
  15. } catch (InvocationTargetException e) {
  16. e.printStackTrace();
  17. } catch (IllegalAccessException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. public static String get(String key) {
  22. try {
  23. Method method = clz().getMethod("get", String.class);
  24. return (String) method.invoke(null, key);
  25. } catch (NoSuchMethodException e) {
  26. e.printStackTrace();
  27. } catch (InvocationTargetException e) {
  28. e.printStackTrace();
  29. } catch (IllegalAccessException e) {
  30. e.printStackTrace();
  31. }
  32. return null;
  33. }

在API19测试,set方法无效,在adb shell 中执行是没有问题的,参考了相关的文章发现原来是 4.4 "KitKat" 的权限问题,即使是反射的调用,set方法修改debug.前缀属性的需要system权限或者shell权限才能修改成功.
解决方案是执行shell的方法来操作,对应的命令是setprop/getprop

Runtime.getRuntime().exec("su setprop key value");


It depends. In the 4.4 "KitKat" release, the list was
contained in init's property_service.c (look around line 65). You can
see, for example, that properties named debug.* can be updated by the
"system" or "shell" user. (The mapping of system-recognized user IDs
to numeric values can be found in android_filesystem_config.h.)

Some properties, such as ro., persist., and ctl.*, have additional
restrictions or special behaviors.

In Android 5.0 "Lollipop", the list moved, but the behavior is the
same.

Use adb shell ps to see what user ID your app is running under. If
it's not system or shell, it won't be able to set system properties.

参考文章:

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注