1. 使用反射獲取
import java.lang.reflect.Method;
public class PropUtils {
/**
* 設置屬性值
*
* @param key 長度不能超過31,key.length <= 30
* @param value 長度不能超過91,value.length<=90
*/
public static void set(String key, String value) {
// android.os.SystemProperties
// public static void set(String key, String val)
try {
Class<?> cls = Class.forName("android.os.SystemProperties");
Method method = cls.getMethod("set", String.class, String.class);
method.invoke(null, key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取屬性值
*
* @param key 長度不能超過31,key.length <= 30
* @param defValue
* @return
*/
public static String get(String key, String defValue) {
// android.os.SystemProperties
// public static String get(String key, String def)
try {
Class<?> cls = Class.forName("android.os.SystemProperties");
Method method = cls.getMethod("get", String.class, String.class);
return (String) method.invoke(null, key, defValue);
} catch (Exception e) {
e.printStackTrace();
}
return defValue;
}
}
2. 添加layoutlib.jar進行使用
jar路徑:D:\Android\sdk\platforms\android-25\data,也可以使用android-其他的,添加到依賴中
3. gradle進行配置操作
在模塊的build.gradle中進行配置,這種方式和2類似,也是添加了jar依賴。
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation files(SDK_DIR() + "/platforms/android-25/data/layoutlib.jar")
}
def SDK_DIR() {
String ret = System.getenv("ANDROID_SDK_HOME")
if (null == ret) {
Properties props = new Properties()
props.load(new FileInputStream(project.rootProject.file("local.properties")))
ret = props.get('sdk.dir')
}
return ret
}
或者
apply plugin: 'com.android.application'
android {
String SDK_DIR = System.getenv("ANDROID_SDK_HOME")
if (SDK_DIR == null) {
Properties props = new Properties()
props.load(new FileInputStream(project.rootProject.file("local.properties")))
SDK_DIR = props.get('sdk.dir')
}
dependencies {
compileOnly files("${SDK_DIR}/platforms/android-19/data/layoutlib.jar")
}
}