安卓(Android) 怎么do shell命令

2019年10月13日15:16:38安卓(Android) 怎么do shell命令已关闭评论 263 1127字阅读3分45秒

1.简介

安卓(Android) 怎么do shell命令?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
import android.util.Log;

public class Main{
    public static int doShellCommand(String[] cmds, ShellCallback sc,
            boolean runAsRoot, boolean waitFor) throws Exception {

        Process proc = null;
        int exitCode = -1;

        if (runAsRoot)
            proc = Runtime.getRuntime().exec("su");
        else
            proc = Runtime.getRuntime().exec("sh");

        final char buf[] = new char[20];

        
        InputStreamReader reader = new InputStreamReader(
                proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            sc.shellOut(buf);
        }

        
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            sc.shellOut(buf);
        }

        OutputStreamWriter out = new OutputStreamWriter(
                proc.getOutputStream());

        for (int i = 0; i < cmds.length; i++) {
            logMessage("executing shell cmd: " + cmds[i] + "; runAsRoot="
                    + runAsRoot + ";waitFor=" + waitFor);

            out.write(cmds[i]);
            out.write("\n");
        }

        out.flush();
        out.write("exit\n");
        out.flush();

        
        

        exitCode = proc.waitFor();

        

        return exitCode;

    }
    public static void logMessage(String msg) {

    }
}

 
继续阅读
编程十万个怎么办