Java code execution shell command
20:48:20
Some system information in Android does not directly provide API interfaces for access. To obtain system information, we need to use shell commands to obtain information. In this case, we can execute commands in the code, it is mainly used hereProcessbuilder
This class.
Code Section:
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) find Viewbyid (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.exe cute (ARGs, "/"); <br/>}catch (ioexception e) {<br/> log. E (TAG, "io1_tio N "); <br/> E. printstacktrace (); <br/>}< br/> return result; <br/>}< br/> private class ShellExecute {<br/>/* <br/> * ARGs [0]: shell commands such as "ls" or "ls-1"; <br/> * ARGs [1]: Command Execution path such "/"; <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 (dire Ctory! = NULL) <br/> builder. directory (new file (directory); <br/> builder. redirecterrorstream (true); <br/> Process = builder. start (); </P> <p> // obtain the command execution result. <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/>}
The layout file is simple and will not be listed.
Execution result: