Android APP执行su命令

通过调用Runtime.getRuntime().exec(“su”);使当前进程获取su权限,然后获取io流,执行命令,获取结果。
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class RootCommand {
    public static String runCommand(String command) {
        Process process = null;
        String result = "";
        DataOutputStream os = null;
        DataInputStream is = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            is = new DataInputStream(process.getInputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            String line = null;
            while ((line = is.readLine()) != null) {
                result += line;
            }
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (process != null) {
                    process.destroy();
                }
        }
        return result;
    }
}

发布了170 篇原创文章 · 获赞 69 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/qq951127336/article/details/88549747
今日推荐