android : how to run a shell command from within c

2019-01-14 10:10发布

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 ?

6条回答
Animai°情兽
2楼-- · 2019-01-14 10:41

You also may remout /system with permissions to write..

查看更多
爷、活的狠高调
3楼-- · 2019-01-14 10:46

The adb shell can behave as a superuser without rooted devices. it's a debug bridge. you can do whatever you want through it.

BUT, when your calling Runtime.getRuntime().exec, you don't have the same premissions. some shell commands aren't even available from exec.

so not only you need a rooted device, you also need su premmisions.

查看更多
走好不送
4楼-- · 2019-01-14 10:46

I think the device will need to be "rooted" for this to work. Have a search on google and see how other developers have dont this, there is no shortage of flashlight apps.

查看更多
做个烂人
5楼-- · 2019-01-14 10:51

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();
}    
查看更多
等我变得足够好
6楼-- · 2019-01-14 10:51

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); 
查看更多
一夜七次
7楼-- · 2019-01-14 10:53

Agreed you probably need to root the phone to write to system files. I'm surprised the brightness isn't exposed through the SDK.

For details on running shell commands from code, check out this project:

查看更多
登录 后发表回答