在 Android 中可以使用反射来调用 SystemProperties 类中的 get() 和 set() 方法来获取和修改 prop 属性
object PropUtils {
private val systemPropertiesClass: Class<*>?
private val getMethod: Method?
private val setMethod: Method?
init {
var clazz: Class<*>? = null
var get: Method? = null
var set: Method? = null
try {
clazz = Class.forName("android.os.SystemProperties")
get = clazz.getMethod("get", String::class.java, String::class.java)
set = clazz.getMethod("set", String::class.java, String::class.java)
} catch (e: Exception) {
e.printStackTrace()
}
systemPropertiesClass = clazz
getMethod = get
setMethod = set
}
fun getProp(key: String,def:String): String? {
return try {
getMethod?.invoke(systemPropertiesClass, key,def) as? String
} catch (e: Exception) {
e.printStackTrace()
null
}
}
fun setProp(key: String, value: String) {
try {
setMethod?.invoke(systemPropertiesClass, key, value)
} catch (e: Exception) {
e.printStackTrace()
}
}
}