2012-06-29 31 views
9

我想要得到android shell命令'getprop'與java的輸出,因爲getprop()總是返回null,無論如何。如何讀取Android進程命令的輸出

我想這從developer.android.com:

 Process process = null; 
    try { 
     process = new ProcessBuilder() 
      .command("/system/bin/getprop", "build.version") 
      .redirectErrorStream(true) 
      .start(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    InputStream in = process.getInputStream(); 

    //String prop = in.toString(); 
    System.out.println(in); 

    process.destroy(); 

但是什麼是印刷不是輸出而是一串字符和數字的(不要有確切的輸出現在)。

我怎樣才能得到這個過程的輸出?

謝謝!

+0

你試過'.getInputStream ().toString();'而不是'.getInputStream();'...只是一個想法 – Zillinium

回答

21

是否有任何特定的原因,爲什麼你想運行該命令作爲外部過程? 有一個簡單的方法:

String android_rel_version = android.os.Build.VERSION.RELEASE; 

但是,如果你真的想通過shell命令來做到這一點,這裏是我得到它的工作方式:

try { 
     // Run the command 
     Process process = Runtime.getRuntime().exec("getprop"); 
     BufferedReader bufferedReader = new BufferedReader(
       new InputStreamReader(process.getInputStream())); 

     // Grab the results 
     StringBuilder log = new StringBuilder(); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      log.append(line + "\n"); 
     } 

     // Update the view 
     TextView tv = (TextView)findViewById(R.id.my_text_view); 
     tv.setText(log.toString()); 
} catch (IOException e) { 
}