安卓(Android) 怎么传入是否 Root 参数执行shell命令

2019年10月13日15:27:29安卓(Android) 怎么传入是否 Root 参数执行shell命令已关闭评论 289 1675字阅读5分35秒

1.简介

安卓(Android) 怎么传入是否 Root 参数执行shell命令?——请看下文。

2.示例代码

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



import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import java.io.InputStream;

public class Main {
    private static int BUFF_LEN = 1024 * 100;
    private static Process sh = null;
    private static Process su = null;

    public static String ExecuteShellCommand(String command,
            Boolean useroot, boolean forcenew) throws Exception {
        byte[] bytes = ExecuteCommand(command, useroot, forcenew);
        String tmp = new String(bytes);
        if (tmp.equals("#null#\n"))
            tmp = "";
        return tmp;
    }

    private static byte[] ExecuteCommand(String command, Boolean useroot,
            boolean forcenew) throws Exception {
        Process p;
        DataOutputStream stdin;
        InputStream stdout;
        ByteArrayOutputStream baos;
        int read;
        byte[] buffer;
        
        command = "RESULT=$("
                + command
                + "); if [[ $RESULT == '' ]]; then echo '#null#';else echo $RESULT;fi\n";

        p = getProcess(useroot, forcenew);

        stdin = new DataOutputStream(p.getOutputStream());
        stdout = p.getInputStream();
        buffer = new byte[BUFF_LEN];
        baos = new ByteArrayOutputStream();

        stdin.writeBytes(command);

        while (true) {
            read = stdout.read(buffer);
            baos.write(buffer, 0, read);
            if (read < BUFF_LEN) {
                
                break;
            }
        }
        if (forcenew) {
            stdin.writeBytes("exit\n");
            stdin.flush();
            stdin.close();
        }

        

        return baos.toByteArray();
    }

    private static Process getProcess(boolean useroot, boolean forcenew)
            throws Exception {

        if (forcenew && useroot)
            return Runtime.getRuntime().exec(new String[] { "su" });
        else if (forcenew && !useroot)
            return Runtime.getRuntime().exec(new String[] { "sh" });
        else if (useroot && su != null)
            return su;
        else if (useroot && su == null) {
            su = Runtime.getRuntime().exec(new String[] { "su" });
            return su;
        } else if (!useroot && sh != null)
            return sh;
        else if (!useroot && sh == null) {
            sh = Runtime.getRuntime().exec(new String[] { "sh" });
            return sh;
        }

        
        return Runtime.getRuntime().exec(new String[] { "sh" });

    }
}

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