安卓(Android) 怎么执行Su且不等待执行结果

2019年10月13日15:18:04安卓(Android) 怎么执行Su且不等待执行结果已关闭评论 355 1571字阅读5分14秒

1.简介

安卓(Android) 怎么执行Su且不等待执行结果?——请看下文。

2.示例代码

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



import java.io.File;
import java.io.IOException;

import java.io.OutputStreamWriter;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;

public class Main {
    private final static String[] BINARY_PLACES = { "/data/bin/",
            "/system/bin/", "/system/xbin/", "/sbin/", "/data/local/xbin/",
            "/data/local/bin/", "/system/sd/xbin/",
            "/system/bin/failsafe/", "/data/local/" };
    private static Boolean IS_ROOTED = null;

    public static Process sudoNoWait(Map<String, String> env,
            String... command) throws Exception {
        if (Boolean.FALSE.equals(IS_ROOTED)) {
            return executeNoWait(env, command);
        }
        
        ProcessBuilder processBuilder = new ProcessBuilder();
        Process process = processBuilder.command(findCommand("su"))
                .redirectErrorStream(true).start();
        OutputStreamWriter stdin = new OutputStreamWriter(
                process.getOutputStream());
        try {
            for (Map.Entry<String, String> entry : env.entrySet()) {
                stdin.write(entry.getKey());
                stdin.write("=");
                stdin.write(entry.getValue());
                stdin.write(" ");
            }
            for (String c : command) {
                stdin.write(c);
                stdin.write(" ");
            }
            stdin.write("\nexit\n");
        } finally {
            stdin.close();
        }
        return process;
    }

    public static Process executeNoWait(Map<String, String> env,
            String... command) throws IOException {
        
        List<String> envp = new ArrayList<String>();
        for (Map.Entry<String, String> entry : env.entrySet()) {
            envp.add(entry.getKey() + "=" + entry.getValue());
        }
        return Runtime.getRuntime().exec(command,
                envp.toArray(new String[envp.size()]));
    }

    public static String findCommand(String command) {
        for (String binaryPlace : BINARY_PLACES) {
            String path = binaryPlace + command;
            if (new File(path).exists()) {
                return path;
            }
        }
        return command;
    }
}

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