我正在尝试使用一些参数进行Instrumentation测试.我注意到我可以通过System.getProperty()函数读取系统属性.所以我使用setprop命令设置系统属性.例如:adb shell setprop AP 123.在我的测试代码中,我尝试用以下内容读取此AP属性:
tmp = System.getProperty("AP");
Log.d("MyTest","AP Value = " + tmp);
Run Code Online (Sandbox Code Playgroud)
然后我使用logcat查看此调试消息,但我得到此属性的空值.关于什么可能出错的任何想法?请注意,我仍然可以使用adb shell getprop AP命令读取系统属性.
acc*_*uya 21
要获得'setprop'设置的属性,有两个选项:
一个.使用android.os.SystemProperties,这是一个隐藏API.像这样用它:
Class clazz = null;
clazz = Class.forName("android.os.SystemProperties");
Method method = clazz.getDeclaredMethod("get", String.class);
String prop = (String)method.invoke(null, "AP");
Log.e("so_test", "my prop is: <" + prop + ">");
Run Code Online (Sandbox Code Playgroud)
二.使用'getprop'工具:
Process proc = Runtime.getRuntime().exec(new String[]{"/system/bin/getprop", "AP"});
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
Log.e("so_test", "my prop is: " + reader.readLine());
Run Code Online (Sandbox Code Playgroud)
也许使用NDK中可用的功能也是一种选择,但为什么要这么麻烦?
Mat*_*ias 14
当根VM(Zygote)启动时,系统属性会被读取一次,这反过来会产生类似应用程序的其他Dalvik VM.这意味着您无法动态设置系统属性.
尝试重启Zygote adb shell stop(等到它停止)和adb shell start(等到它重新启动),然后再试一次.或者只是重启设备或模拟器.
小智 9
因为Android中有两种类型的属性.
adb shell getprop/setprop.System.getProperty()/setProperty().在设置系统级属性并尝试将其值作为当前进程级别时,您将在日志中获取空值.
这是一个基于accuya答案的略显理智的版本:
public static String readSystemProperty(String name) {
InputStreamReader in = null;
BufferedReader reader = null;
try {
Process proc = Runtime.getRuntime().exec(new String[]{"/system/bin/getprop", name});
in = new InputStreamReader(proc.getInputStream());
reader = new BufferedReader(in);
return reader.readLine();
} catch (IOException e) {
return null;
} finally {
closeQuietly(in);
closeQuietly(reader);
}
}
public static void closeQuietly(Closeable closeable) {
if (closeable == null) return;
try {
closeable.close();
} catch (IOException ignored) {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54656 次 |
| 最近记录: |