android : how to run a shell command from within code(android:如何在代码中运行 shell 命令)

本文介绍了android:如何在代码中运行 shell 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的代码中执行一个命令,命令是echo 125 >/sys/devices/platform/flashlight.0/leds/flashlight/brightness"我可以从 adb shell 毫无问题地运行它

I am trying to execute a command from within my code, the command is "echo 125 > /sys/devices/platform/flashlight.0/leds/flashlight/brightness" and I can run it without problems from adb shell

我正在使用 Runtime 类来执行它:

I am using Runtime class to execute it :

Runtime.getRuntime().exec("echo 125 > /sys/devices/platform/flashlight.0/leds/flashlight/brightness");

但是我得到一个权限错误,因为我不应该访问 sys 目录.我还尝试将命令放在 String[] 中,以防空格引起问题,但并没有太大区别.

However I get a permissions error since I am not supposed to access the sys directory. I have also tried to place the command in a String[] just in case spaces caused a problem but it didn't make much differense.

有没有人知道任何解决方法?

Does anyone know any workaround for this ?

推荐答案

手机需要root,之后你可以这样做:

The phone needs to be rooted, afterwards you can do something like:

public static void doCmds(List<String> cmds) throws Exception {
    Process process = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(process.getOutputStream());

    for (String tmpCmd : cmds) {
            os.writeBytes(tmpCmd+"
");
    }

    os.writeBytes("exit
");
    os.flush();
    os.close();

    process.waitFor();
}    

这篇关于android:如何在代码中运行 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!