前言
大家可能知道,使用adb shell getprop命令可以直接获取系统属性值,但有时候需要在JAVA代码中获取系统属性,接下来说一下如何实现。
代码实现
在build.gradle的android下中添加如下代码,以找到android.os.SystemProperties类:
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-21/data/layoutlib.jar")
}
完整的build.gradle示例文件如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.testsystemproperty"
minSdkVersion 14
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
//以下是为了找到android.os.SystemProperties这个隐藏的类
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-21/data/layoutlib.jar")
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
在代码中需要获取系统属性的地方调用android.os.SystemProperties类的get接口获取系统属性值,以下为示例代码:
package com.example.testsystemproperty;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static String propertyName = "ro.system.build.date"; //根据需要获取的属性名称修改
private TextView textView1;
private TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = findViewById(R.id.tv1);
textView2 = findViewById(R.id.tv2);
textView1.setText("propertyName:" + propertyName);
textView2.setText("propertyValue:" + android.os.SystemProperties.get(propertyName,""));
}
}
最后在安卓设备运行一下查看效果: