歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Android中級篇之用JAVA代碼執行shell命令

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

日期:2017/3/1 10:50:22   编辑: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. mButton.setOnClickListener(new OnClickListener() {
  23. public void onClick(View v) {
  24. myTextView.setText(getResult());
  25. }
  26. });
  27. }
  28. public String getResult(){
  29. ShellExecute cmdexe = new ShellExecute ( );
  30. String result="";
  31. try {
  32. result = cmdexe.execute(ARGS, "/");
  33. } catch (IOException e) {
  34. Log.e(TAG, "IOException");
  35. e.printStackTrace();
  36. }
  37. return result;
  38. }
  39. private class ShellExecute {
  40. /*
  41. * args[0] : shell 命令 如"ls" 或"ls -1";
  42. * args[1] : 命令執行路徑 如"/" ;
  43. */
  44. public String execute ( String [] cmmand,String directory)
  45. throws IOException {
  46. String result = "" ;
  47. try {
  48. ProcessBuilder builder = new ProcessBuilder(cmmand);
  49. if ( directory != null )
  50. builder.directory ( new File ( directory ) ) ;
  51. builder.redirectErrorStream (true) ;
  52. Process process = builder.start ( ) ;
  53. //得到命令執行後的結果
  54. InputStream is = process.getInputStream ( ) ;
  55. byte[] buffer = new byte[1024] ;
  56. while ( is.read(buffer) != -1 ) {
  57. result = result + new String (buffer) ;
  58. }
  59. is.close ( ) ;
  60. } catch ( Exception e ) {
  61. e.printStackTrace ( ) ;
  62. }
  63. return result ;
  64. }
  65. }
  66. }

布局文件很簡單就不列出了

Copyright © Linux教程網 All Rights Reserved