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



代码部分 :

[java] view plain copy
  1. packagecom.yin.system_analysis;
  2. importjava.io.File;
  3. importjava.io.IOException;
  4. importjava.io.InputStream;
  5. importandroid.app.Activity;
  6. importandroid.os.Bundle;
  7. importandroid.util.Log;
  8. importandroid.view.View;
  9. importandroid.view.View.OnClickListener;
  10. importandroid.widget.Button;
  11. importandroid.widget.TextView;
  12. publicclassMainActivityextendsActivity{
  13. privatefinalstaticString[]ARGS={"ls","-l"};
  14. privatefinalstaticStringTAG="com.yin.system";
  15. ButtonmButton;
  16. TextViewmyTextView;
  17. publicvoidonCreate(BundlesavedInstanceState){
  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(newOnClickListener(){
  23. publicvoidonClick(Viewv){
  24. myTextView.setText(getResult());
  25. }
  26. });
  27. }
  28. publicStringgetResult(){
  29. ShellExecutecmdexe=newShellExecute();
  30. Stringresult="";
  31. try{
  32. result=cmdexe.execute(ARGS,"/");
  33. }catch(IOExceptione){
  34. Log.e(TAG,"IOException");
  35. e.printStackTrace();
  36. }
  37. returnresult;
  38. }
  39. privateclassShellExecute{
  40. /*
  41. *args[0]:shell命令如"ls"或"ls-1";
  42. *args[1]:命令执行路径如"/";
  43. */
  44. publicStringexecute(String[]cmmand,Stringdirectory)
  45. throwsIOException{
  46. Stringresult="";
  47. try{
  48. ProcessBuilderbuilder=newProcessBuilder(cmmand);
  49. if(directory!=null)
  50. builder.directory(newFile(directory));
  51. builder.redirectErrorStream(true);
  52. Processprocess=builder.start();
  53. //得到命令执行后的结果
  54. InputStreamis=process.getInputStream();
  55. byte[]buffer=newbyte[1024];
  56. while(is.read(buffer)!=-1){
  57. result=result+newString(buffer);
  58. }
  59. is.close();
  60. }catch(Exceptione){
  61. e.printStackTrace();
  62. }
  63. returnresult;
  64. }
  65. }
  66. }

更多相关文章

  1. 配置ionic+Android开发环境
  2. Android(安卓)Info类的总结
  3. 在Android模拟器中模拟GPS、打电话、发短信
  4. Android(安卓)unbindservice异常相关问题
  5. Android开发之获取SHA1
  6. Xposed Android(安卓)hook -方法介绍
  7. Android模拟器SD卡的使用
  8. 第2.3节 android目录中manifest的介绍
  9. [android]MonkeyRunner-andrec实现思路

随机推荐

  1. android ImageView scaleType属性
  2. 圆圈里面是个叉号
  3. Android(安卓)Building System 分析
  4. mainfest文件中android属性
  5. Failed to fetch URL https://dl-ssl.goo
  6. android系统中自带的图标大全
  7. API 23 widget.ProgressBar——属性分析
  8. API 23 widget.ImageView——属性分析
  9. Android,visibility属性
  10. android 录像和拍照功能