Android executes command lines in Android code and android command lines

Source: Internet
Author: User

Android executes command lines in Android code and android command lines

1. The path should not be your own spelling path/mnt/shell/emulated/0/wifidog. conf

It is best to obtain the path through the method, otherwise the command may be invalid (the reason for the mount point)

Public static final String SDCARD_ROOT = Environment. getExternalStorageDirectory (). getAbsolutePath ();

Public static final String AAA_PATH = SDCARD_ROOT + "/wifidog. conf ";

 

Android command line execution Tool

Package com. example. videotest. utils; import android. OS. environment; import android. util. log; import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. inputStreamReader; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. readWriteLock; import java. util. concurrent. locks. reentrantReadWriteLock; import static java. lang. runtime. getRuntime;/*** Command Execution class * Created by Kap Pa */public class ExeCommand {// shell Process private process Process; // The three streams of the corresponding process: private BufferedReader successResult; private BufferedReader errorResult; private DataOutputStream OS; // whether to synchronize, true: run is always blocked until it is completed or timed out. False: run immediately returns private boolean bSynchronous; // indicates whether the shell process is still running private boolean bRunning = false; // ReadWriteLock lock = new ReentrantReadWriteLock (); // Save the execution result private StringBuffer result = new StringBuffer ();/*** constructor ** @ param synchronous true: synchronous, false: asynchronous */public ExeCommand (boolean synchronous) {bSynchronous = synchronous;}/*** default constructor. The default constructor is synchronous execution */public ExeCommand () {bSynchronous = tr Ue;}/*** execution not started yet, and execution completed both return false ** @ return whether execution is in progress */public boolean isRunning () {return bRunning;}/*** @ return returns the execution result */public String getResult () {Lock readLock = lock. readLock (); readLock. lock (); try {Log. I ("auto", "getResult"); return new String (result);} finally {readLock. unlock () ;}/ ***** run the command ** @ param command eg: cat/sdcard/test.txt *. It is best not to use your own spelling path, it is best to obtain the path * exam through the method. Ple: Environment. getExternalStorageDirectory () * @ param maxTime maximum wait time (MS) * @ return this */public ExeCommand run (String command, final int maxTime) {Log. I ("auto", "run command:" + command + ", maxtime:" + maxTime); if (command = null | command. length () = 0) {return this;} try {process = getruntime(cmd.exe c ("sh"); // It may be su} catch (Exception e) {return this;} bRunning = true; successResult = New BufferedReader (new InputStreamReader (process. getInputStream (); errorResult = new BufferedReader (new InputStreamReader (process. getErrorStream (); OS = new DataOutputStream (process. getOutputStream (); try {// write the OS command to be executed to sh. write (command. getBytes (); OS. writeBytes ("\ n"); OS. flush (); OS. writeBytes ("exit \ n"); OS. flush (); OS. close (); // if the wait time is set to a non-positive value, the timeout close function is not enabled if (maxTime> 0) {// The process new T is disabled upon timeout Hread (new Runnable () {@ Override public void run () {try {Thread. sleep (maxTime);} catch (Exception e) {} try {int ret = process. exitValue (); Log. I ("auto", "exitValue Stream over" + ret);} catch (IllegalThreadStateException e) {Log. I ("auto", "take maxTime, forced to destroy process"); process. destroy ();}}}). start () ;}// open a Thread to process the input stream final Thread t1 = new Thread (new Runnable () {@ Override pu Blic void run () {String line; Lock writeLock = lock. writeLock (); try {while (line = successResult. readLine ())! = Null) {line + = "\ n"; writeLock. lock (); result. append (line); writeLock. unlock () ;}} catch (Exception e) {Log. I ("auto", "read InputStream exception:" + e. toString ();} finally {try {successResult. close (); Log. I ("auto", "read InputStream over");} catch (Exception e) {Log. I ("auto", "close InputStream exception:" + e. toString () ;}}}); t1.start (); // open a Thread to handle the error stream final Thread t2 = new Thr Ead (new Runnable () {@ Override public void run () {String line; Lock writeLock = lock. writeLock (); try {while (line = errorResult. readLine ())! = Null) {line + = "\ n"; writeLock. lock (); result. append (line); writeLock. unlock () ;}} catch (Exception e) {Log. I ("auto", "read ErrorStream exception:" + e. toString ();} finally {try {errorResult. close (); Log. I ("auto", "read ErrorStream over");} catch (Exception e) {Log. I ("auto", "read ErrorStream exception:" + e. toString () ;}}}); t2.start (); Thread t3 = new Thread (new Runnable () {@ Override public void run () {try {// wait until execution is completed t1.join (); t2.join (); process. waitFor ();} catch (Exception e) {} finally {bRunning = false; Log. I ("auto", "run command process end") ;}}); t3.start (); if (bSynchronous) {Log. I ("auto", "run is go to end"); t3.join (); Log. I ("auto", "run is end") ;}} catch (Exception e) {Log. I ("auto", "run command process exception:" + e. toString () ;}return this ;}}

The key point is to start a sh process. If you are using a root device, you can use su.

This process contains three streams: input, output, and error. These three streams must be processed properly. Otherwise, the process may not be properly terminated,

In addition, the execution of the command has ended, but the input stream still exists, which also needs to be processed.

For more information, see the code.

 

There are two usage methods. The first is the blocking method. This call method will always be blocked until the command execution is complete and return the output result of the command line.

Public static final String SDCARD_ROOT = Environment. getExternalStorageDirectory (). getAbsolutePath (); public static final String AAA_PATH = SDCARD_ROOT + "/wifidog. conf "; // read the String cmd3 =" sed-n "/# TrustedMACList/of the specified content" # TrustedMACList "in the target file (absolute path /, // p '"+ AAA_PATH; String str3 = new ExeCommand (). running (cmd3, 10000 ). getResult (); Log. I ("auto", str3 + "button3"); Toast. makeText (MainActivity. this, str3, Toast. LENGTH_SHORT ). show ();

LOG program execution sequence

I/auto    ( 5542): run command:sed -n '/#TrustedMACList /,//p' /storage/emulated/0/wifidog.conf,maxtime:10000I/auto    ( 5542): run is go to endI/auto    ( 5542): read ErrorStream overI/auto    ( 5542): read InputStream overI/auto    ( 5542): run command process endI/auto    ( 5542): run is endI/auto    ( 5542): getResultI/auto    ( 5542): #TrustedMACList 00:00:C0:1D:F0:0D,00:00:C0:1D:F0:0D,00:00:C0:1D:F0:0D,00:00:C0:1D:F0:0D,00:00:C0:1D:F0:0D,00:00:DE:AD:BE:AF,00:00:C0:1D:F0:0DI/auto    ( 5542): I/auto    ( 5542): button3

 

 

 

Another method is asynchronous. This method will directly return the result. You can use getResult () to obtain the result and use isRunning () to determine whether the result is complete. For example

 ExeCommand cmd = new ExeCommand(false).run("your cmd", 60000);    while(cmd.isRunning())    {        try {            sleep(1000);        } catch (Exception e) {        }        String buf = cmd.getResult();        //do something    }

 

 

 

 

 

 

 

// Modify the specified content of the target file "# TrustedMACList"
String cmd = "sed-I's/# TrustedMACList 00: 00: C0: 1D: F0: 0D,/G'" + AAA_PATH; string str = new ExeCommand (). run (cmd, 10000 ). getResult (); Log. I ("auto", str + "button4"); Toast. makeText (MainActivity. this, str, Toast. LENGTH_SHORT ). show ();

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.