對于基于系統平臺開發應用的開發者來說,在一些應用場景下常常需要我們獲取系統隱藏API來處理問題,下面我們以獲取系統的屬性為例子展開詳細地說明。
首先明確哪類屬于系統隱藏api呢?
如系統屬性類 SystemProperties.java
,
代碼位于frameworks/base/core/java/android/os/SystemProperties.java
package android.os;
import java.util.ArrayList;
import android.util.Log;
/**
* Gives access to the system properties store. The system properties
* store contains a list of string key-value pairs.
*
* {@hide}
*/
public class SystemProperties
{
//略
/**
* Get the value for the given key.
* @return if the key isn't found, return def if it isn't null, or an empty string otherwise
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(String key, String def) {
if (key.length() > PROP_NAME_MAX) {
throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX);
}
return native_get(key, def);
}
//略
}
注意上面的 {@hide}
這個anotation的聲明,只要標注了這個anotation的類或者方法,在標準的sdk中是無法直接引用的。
如何使用Java反射機制引用
什么是Java的反射機制,這個相信大家都是有所了解的,下面直接上代碼
public static String systemPropertiesGet(String prop, String defVal) {
try {
//通過詳細地類名獲取到指定的類
Class<?> psirClass = Class.forName("android.os.SystemProperties");
//通過方法名,傳入參數獲取指定方法
java.lang.reflect.Method method = psirClass.getMethod("get", String.class, String.class);
String ret = (String) method.invoke(psirClass.newInstance(), prop, defVal);
return ret;
} catch (Exception e) {
}
return defVal;
}
通過以上的方法就可以獲取到系統隱藏的api來幫助我們處理問題了,這里相當于引用了SystemProperties.get(String key, String def)
方法。