Android中级篇之用JAVA代码执行shell命令


在Android可能有的系统信息没有直接提供API接口来访问,为了获取系统信息时我们就要在用shell指令来获取信息,这时我们可以在代码中来执行命令 ,这里主要用到ProcessBuilder 这个类.

代码部分  :

  1. package com.yin.system_analysis;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.TextView;  
  12. public class MainActivity extends Activity {  
  13.     private final static String[] ARGS = {"ls","-l"};  
  14.     private final static String TAG = "com.yin.system";  
  15.     Button mButton;  
  16.     TextView myTextView;  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.         mButton = (Button) findViewById(R.id.myButton);  
  21.         myTextView = (TextView) findViewById(R.id.textView);  
  22.           
  23.         mButton.setOnClickListener(new OnClickListener() {  
  24.               
  25.             public void onClick(View v) {  
  26.                   
  27.                 myTextView.setText(getResult());  
  28.             }  
  29.         });  
  30.     }  
  31.     public String getResult(){  
  32.          ShellExecute cmdexe = new ShellExecute ( );  
  33.          String result="";  
  34.          try {  
  35.             result = cmdexe.execute(ARGS, "/");  
  36.         } catch (IOException e) {  
  37.             Log.e(TAG, "IOException");  
  38.             e.printStackTrace();  
  39.         }  
  40.         return result;  
  41.     }  
  42.     private class ShellExecute {  
  43.         /* 
  44.          * args[0] : shell 命令  如"ls" 或"ls -1"; 
  45.          * args[1] : 命令执行路径  如"/" ; 
  46.          */  
  47.         public String execute ( String [] cmmand,String directory)  
  48.         throws IOException {  
  49.         String result = "" ;  
  50.         try {  
  51.         ProcessBuilder builder = new ProcessBuilder(cmmand);  
  52.           
  53.         if ( directory != null )  
  54.         builder.directory ( new File ( directory ) ) ;  
  55.         builder.redirectErrorStream (true) ;  
  56.         Process process = builder.start ( ) ;  
  57.           
  58.         //得到命令执行后的结果   
  59.         InputStream is = process.getInputStream ( ) ;  
  60.         byte[] buffer = new byte[1024] ;  
  61.         while ( is.read(buffer) != -1 ) {  
  62.         result = result + new String (buffer) ;  
  63.         }  
  64.         is.close ( ) ;  
  65.         } catch ( Exception e ) {  
  66.             e.printStackTrace ( ) ;  
  67.         }  
  68.         return result ;  
  69.         }  
  70.     }  
  71. }  

布局文件很简单就不列出了   

相关内容