How to read Android properties with Java
There actually is a system side implementation of the getprop
call. It is called Systemproperties.get()
and can be found here. For users, that work on system code inside the AOSP, or do want to take the risk of using reflect
, this is the way to go.
In case someone wanted to know my solution... with George's help I ended up using this:
private String propReader() {
Process process = null;
try {
process = new ProcessBuilder().command("/system/bin/getprop")
.redirectErrorStream(true).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream in = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("dolby"))
log.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(in);
process.destroy();
return log.toString();
}
I cleaned up TMont's solution and made it more generic (added parameter for propertyName):
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SystemProperties {
private static String GETPROP_EXECUTABLE_PATH = "/system/bin/getprop";
private static String TAG = "MyApp";
public static String read(String propName) {
Process process = null;
BufferedReader bufferedReader = null;
try {
process = new ProcessBuilder().command(GETPROP_EXECUTABLE_PATH, propName).redirectErrorStream(true).start();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = bufferedReader.readLine();
if (line == null){
line = ""; //prop not set
}
Log.i(TAG,"read System Property: " + propName + "=" + line);
return line;
} catch (Exception e) {
Log.e(TAG,"Failed to read System Property " + propName,e);
return "";
} finally{
if (bufferedReader != null){
try {
bufferedReader.close();
} catch (IOException e) {}
}
if (process != null){
process.destroy();
}
}
}
}