Android: how to run a shell command from code
I am trying to execute a command from my code, the command "echo 125> /sys/devices/platform/flashlight.0/leds/flashlight/brightness" and I can run it without problems from the adb shell
I use the Runtime class to execute it:
Runtime.getRuntime().exec("echo 125 > /sys/devices/platform/flashlight.0/leds/flashlight/brightness");
However, I get a permissions error, since I should not access the sys directory. I also tried to put the command in String [] only if the spaces caused the problem, but it did not differ much.
Does anyone know of a workaround for this?
The phone should be rooted, after which 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+"\n"); } os.writeBytes("exit\n"); os.flush(); os.close(); process.waitFor(); }
If you're just trying to set the brightness, why don't you do it through the provided API (AKA, is there a reason why you are trying to do it the way you are).
int brightness = 125; Settings.System.putInt( ftaContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
The adb shell can act as root without root devices. This is a debugging bridge. you can do whatever you want through it.
BUT when you call Runtime.getRuntime (). exec, you do not have the same sentences. some shell commands are not even accessible from exec.
therefore, you need not only a rooted device, but you also need preliminary solutions.