Android 應用利用反射機制獲取/設定系統屬性值
阿新 • • 發佈:2019-02-07
使用adb shell 中的getprop 可以獲取屬性的值,但是在應用開發中因為systemproperties的hide屬性,所以無法直接訪問到get和set函式。
通過網上的教程可以通過反射機制來獲取get和set函式,具體程式碼如下:
<span style="font-family:Microsoft YaHei;">/* * method to setprop * */ static public void setprop(String key, String defaultValue) { String value = defaultValue; 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(); } }</span>
接下來看看反射機制。<span style="font-family:Microsoft YaHei;">/* * method to getprop * */ static 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; } }</span>