Android中級篇之用JAVA代碼執行shell命令

來源:互聯網
上載者:User

JAVA代碼執行shell命令

2011-06-07   20:48:20

      在Android可能有的系統資訊沒有直接提供API介面來訪問,為了擷取系統資訊時我們就要在用shell指令來擷取資訊,這時我們可以在代碼中來執行命令 ,這裡主要用到ProcessBuilder

這個類.



代碼部分  :

package com.yin.system_analysis;<br />import java.io.File;<br />import java.io.IOException;<br />import java.io.InputStream;<br />import android.app.Activity;<br />import android.os.Bundle;<br />import android.util.Log;<br />import android.view.View;<br />import android.view.View.OnClickListener;<br />import android.widget.Button;<br />import android.widget.TextView;<br />public class MainActivity extends Activity {<br />private final static String[] ARGS = {"ls","-l"};<br />private final static String TAG = "com.yin.system";<br />Button mButton;<br />TextView myTextView;<br />public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);<br /> mButton = (Button) findViewById(R.id.myButton);<br /> myTextView = (TextView) findViewById(R.id.textView);</p><p> mButton.setOnClickListener(new OnClickListener() {</p><p>public void onClick(View v) {</p><p>myTextView.setText(getResult());<br />}<br />});<br /> }<br /> public String getResult(){<br /> ShellExecute cmdexe = new ShellExecute ( );<br /> String result="";<br /> try {<br />result = cmdexe.execute(ARGS, "/");<br />} catch (IOException e) {<br />Log.e(TAG, "IOException");<br />e.printStackTrace();<br />}<br />return result;<br /> }<br /> private class ShellExecute {<br /> /*<br /> * args[0] : shell 命令 如"ls" 或"ls -1";<br /> * args[1] : 命令執行路徑 如"/" ;<br /> */<br /> public String execute ( String [] cmmand,String directory)<br /> throws IOException {<br /> String result = "" ;<br /> try {<br /> ProcessBuilder builder = new ProcessBuilder(cmmand);</p><p> if ( directory != null )<br /> builder.directory ( new File ( directory ) ) ;<br /> builder.redirectErrorStream (true) ;<br /> Process process = builder.start ( ) ;</p><p> //得到命令執行後的結果<br /> InputStream is = process.getInputStream ( ) ;<br /> byte[] buffer = new byte[1024] ;<br /> while ( is.read(buffer) != -1 ) {<br /> result = result + new String (buffer) ;<br /> }<br /> is.close ( ) ;<br /> } catch ( Exception e ) {<br /> e.printStackTrace ( ) ;<br /> }<br /> return result ;<br /> }<br /> }<br />}

布局檔案很簡單就不列出了   

執行結果 :

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.