How to read Android properties with Java

TMont picture TMont · Jan 26, 2015 · Viewed 15.6k times · Source

I use 'adb shell getprop' in the terminal. What interfaces can I use in Android JAVA to get the same information?

I have tried several things like:

Properties sysProps = System.getProperties();

But I don't think these are the same properties I am looking for? Specifically, I want to find values that will return similar to the following:

adb shell getprop | grep dolby

The shell 'grep dolby' command returns this:

[audio.dolby.ds2.enabled]: [true] 
[dolby.audio.sink.info]: [headset] 
[dolby.ds.dialogenhancer.state]: [on] 
[dolby.ds.graphiceq.state]: [off] 
[dolby.ds.hpvirtualizer.state]: [off] 
[dolby.ds.intelligenteq.preset]: [Off] 
[dolby.ds.intelligenteq.state]: [off] 
[dolby.ds.platform]: [qcom] 
[dolby.ds.profile.name]: [Movie] 
[dolby.ds.spkvirtualizer.state]: [off] 
[dolby.ds.state]: [off] 
[dolby.ds.volumeleveler.state]: [on] 

But I want to access this information in Android JAVA code.

Any ideas?

Answer

Florian Bramer picture Florian Bramer · Jan 13, 2017

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();
            }
        }
    }
}