Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android : how to run a shell command from within code

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

I am using 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 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 ?

like image 559
ee3509 Avatar asked Dec 03 '22 05:12

ee3509


2 Answers

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+"\n");
    }

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

    process.waitFor();
}    
like image 193
Loxley Avatar answered Jan 03 '23 17:01

Loxley


If you're just trying to set brightness, why don't you do so through the provided API (AKA, is there a reason you are trying to do it the way you are).

int brightness = 125; 
Settings.System.putInt(
      ftaContext.getContentResolver(), 
      Settings.System.SCREEN_BRIGHTNESS, 
      brightness); 
like image 40
JasCav Avatar answered Jan 03 '23 18:01

JasCav