Android P App中调用Shell命令

Android中可以执行很多Shell命令。

例如:

//测试网络能否ping通 -c 10 指发送10个数据包测试
ping -c 10 192.168.10.22
//查看目录
ls
//am start命令启动Settings程序
am start -n com.android.settings/com.android.settings.Settings --display 0

有时候,我们需要在App程序中去执行这些命令。

ShellUtils

public class ShellUtils {
    private static final String TAG = "ShellUtils";

    public static final String COMMAND_SU = "su";
    public static final String COMMAND_SH = "sh";
    public static final String COMMAND_EXIT = "exit\n";
    public static final String COMMAND_LINE_END = "\n";

    private ShellUtils() {
        throw new AssertionError();
    }

    /**
     * 查看是否有了root权限
     *
     * @return
     */
    public static boolean checkRootPermission() {
        return execCommand("echo root", true, false).result == 0;
    }

    /**
     * 执行shell命令,默认返回结果
     *
     * @param command
     *            command
     * @param isRoot
     *              need root permission
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(String command, boolean isRoot) {
        return execCommand(new String[] { command }, isRoot, true);
    }

    /**
     * 执行shell命令,默认返回结果
     *
     * @param commands
     *            command list
     * @param isRoot
     *              need root permission
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(List<String> commands,
                                            boolean isRoot) {
        return execCommand(
                commands == null ? null : commands.toArray(new String[] {}),
                isRoot, true);
    }

    /**
     * 执行shell命令,默认返回结果
     *
     * @param commands
     *            command array
     * @param isRoot
     *              need root permission
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(String[] commands, boolean isRoot) {
        return execCommand(commands, isRoot, true);
    }

    /**
     * execute shell command
     *
     * @param command
     *            command
     * @param isRoot
     *              need root permission
     * @param isNeedResultMsg
     *            whether need result msg
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(String command, boolean isRoot,
                                            boolean isNeedResultMsg) {
        return execCommand(new String[] { command }, isRoot, isNeedResultMsg);
    }

    /**
     * execute shell commands
     *
     * @param commands
     *            command list
     * @param isRoot
     *              need root permission
     * @param isNeedResultMsg
     *              result
     * @return
     * @see ShellUtils#execCommand(String[], boolean, boolean)
     */
    public static CommandResult execCommand(List<String> commands,
                                            boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(
                commands == null ? null : commands.toArray(new String[] {}),
                isRoot, isNeedResultMsg);
    }

    /**
     * execute shell commands
     *
     * @param commands
     *              command array
     * @param isRoot
     *              need root permission
     * @param isNeedResultMsg
     *              result
     * @return <ul>
     *         <li>if isNeedResultMsg is false, {@link CommandResult#successMsg}
     *         is null and {@link CommandResult#errorMsg} is null.</li>
     *         <li>if {@link CommandResult#result} is -1, there maybe some
     *         excepiton.</li>
     *         </ul>
     */
    public static CommandResult execCommand(String[] commands, boolean isRoot,
                                            boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;

        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null) {
                    continue;
                }
                // donnot use os.writeBytes(commmand), avoid chinese charset
                // error
                os.write(command.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();
            result = process.waitFor();
            // get command result
            if (isNeedResultMsg) {
                successMsg = new StringBuilder();
                errorMsg = new StringBuilder();
                successResult = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(
                        process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return new CommandResult(result, successMsg == null ? null
                : successMsg.toString(), errorMsg == null ? null
                : errorMsg.toString());
    }

    /**
     * 运行结果
     * <ul>
     * <li>{@link CommandResult#result} means result of command, 0 means normal,
     * else means error, same to excute in linux shell</li>
     * <li>{@link CommandResult#successMsg} means success message of command
     * result</li>
     * <li>{@link CommandResult#errorMsg} means error message of command result</li>
     * </ul>
     *
     * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a>
     *         2013-5-16
     */
    public static class CommandResult {
        /** 运行结果 **/
        public int result;
        /** 运行成功结果 **/
        public String successMsg;
        /** 运行失败结果 **/
        public String errorMsg;

        public CommandResult(int result) {
            this.result = result;
        }

        public CommandResult(int result, String successMsg, String errorMsg) {
            this.result = result;
            this.successMsg = successMsg;
            this.errorMsg = errorMsg;
        }
    }
}

调用

ShellUtils.CommandResult result1 = ShellUtils.execCommand("/system/bin/ping -c 10 192.168.10.22",false);
Log.i(TAG,"result1.result = " + result1.result);
Log.i(TAG,"result1.successMsg = " + result1.successMsg);
Log.i(TAG,"result1.errorMsg = " + result1.errorMsg);

ShellUtils.CommandResult result2 = ShellUtils.execCommand(“ls”,false);
Log.i(TAG,"result2.result = " + result2.result);
Log.i(TAG,"result2.successMsg = " + result2.successMsg);
Log.i(TAG,"result2.errorMsg = " + result2.errorMsg);

出错

注意调用的方法: ShellUtils.execCommand(“ls”,false);和 ShellUtils.execCommand(“ls”,true);的区别

false,是指该命令不需要su权限,root权限。
true,表示该命令需要su权限和root权限。

但是在大部分机器中,app是没有root的权限的,所以有些命令是无法执行的。
报错:
su:not allowed
start:must be root

目前没有找到App能获取到root权限的方法。故,目前只能执行一些不需要root权限的命令。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
Android应用执行Shell命令可以过`Runtime.getRuntime().exec(command)`方法来实现,其`command`是要执行的Shell命令字符串,比如`am start -n com.example.app/.MainActivity`。 要实现从一个Android应用跳转到另一个应用,可以调用Shell命令来执行`am start`命令。`am start`命令用于启动一个指定应用的特定Activity。 首先,需要确保设备已经root或者应用拥有相应的系统权限,才能执行Shell命令。然后,在应用过`Runtime.getRuntime().exec()`方法执行Shell命令。 下面是一个示例代码: ```java try { // 构建要执行的命令 String packageName = "com.example.app"; String activityName = "com.example.app.MainActivity"; String command = "am start -n " + packageName + "/" + activityName; // 执行Shell命令 Process process = Runtime.getRuntime().exec(command); // 读取命令结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { Log.d("Shell", line); } // 等待命令执行完成 process.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } ``` 上述代码,将要跳转的应用的包名和Activity名拼接成一个命令字符串,然后过`Runtime.getRuntime().exec()`方法执行Shell命令。读取命令结果可以过`InputStreamReader`和`BufferedReader`来实现,可以根据需要处理命令输出的结果。最后使用`process.waitFor()`等待命令执行完成。 需要注意的是,执行Shell命令需要小心处理,确保没有安全隐患。同时,要避免滥用Shell命令,以免影响到设备的正常运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunxiaolin2016

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值