Android intermediate Java Code Execution Shell command
[Date: 2011-12-08] Source: Linux Community y13872888163
There may be system information on Android not directly provided API interface to access, in order to obtain system information we have to use shell instructions to obtain information, we can execute commands in the code, the main use of Processbuilder this class.
Code section:
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. Public classMainactivityextendsActivity {13.Private Final StaticString[] ARGS = {"ls", "-L"};14.Private Final StaticString TAG = "Com.yin.system";15. Button Mbutton; 16. TextView Mytextview; 17. Public voidonCreate (Bundle savedinstancestate) {18.Super. OnCreate (savedinstancestate);19. Setcontentview (R.layout.main); Mbutton =(Button) Findviewbyid (R.id.mybutton); Mytextview =(TextView) Findviewbyid (R.id.textview); 22. Mbutton.setonclicklistener (NewOnclicklistener () {24. 25. Public voidOnClick (View v) {26. 27. Mytextview.settext (GetResult ()); 28. } 29. }); 30. } 31. PublicString GetResult () {ShellExecute CmdExe =NewShellExecute ();. String result= "";34.Try {result = Cmdexe.execute (ARGS, "/");36.}Catch(IOException e) {Panax Notoginseng log.e (TAG, "IOException"));38. E.printstacktrace (); 39. } 40.returnresult;41. } 42.Private classShellExecute {43./** Args[0]: Shell commands such as "LS" or "ls-1"; 45. * args[1]: Command execution path such as "/"; 46. */47. Publicstring Execute (string [] cmmand,string directory)48.throwsIOException {. String result = "" ; 50.Try { Wuyi Processbuilder builder =NewProcessbuilder (Cmmand); 52. 53.if(Directory! =NULL ) Builder.directory (NewFile (directory)); Builder.redirecterrorstream (true) ; . Process Process =Builder.start (); 57. 58.//get the result after the command executesInputStream is =Process.getinputstream (); 60.byte[] buffer =New byte[1024] ; 61. while(Is.read (buffer)! =-1 ) { . result = result +NewString (buffer); 63. } 64. Is.close (); 65.}Catch(Exception e) {66. E.printstacktrace (); 67. } 68.returnresult; 69. } 70. } 71.}
The layout file is simply not listed
This article is from the Linux commune website (www.linuxidc.com) Source Link: http://www.linuxidc.com/Linux/2011-12/48958.htm
This article is reproduced in others,:-D
Android Java Code Execution Shell command