Android- performing su commands programatically does not work

LoneDuck picture LoneDuck · Apr 20, 2015 · Viewed 16.4k times · Source

I need my app to perform some su commands programatically (phone is rooted).

When done using adb, the commands work.

For instance: su -c "mkdir /sdcard/testdir" creates a directory called "testdir" in /sdcard.

When I call:

    p = Runtime.getRuntime().exec("su -c \"mkdir /sdcard/testdir\"");
    p.waitFor();

It just moves on and no change happens.

I tried reading the input:

DataInputStream dis = new DataInputStream(p.getInputStream());
    while((temp = dis.readLine())!=null)
        Log.d(ctx.TAG,"shell:"+temp);

But it reports nothing (loop does 0 iterations).

Has anyone ever faced this issue before? How can it be solved? Needless to day, non-su commands do work programatically with this method.

Note: I gave mkdir as an example (I know it doesn't necessarily require su). I need a lot of varied commands to be performed under su

Thank you!

EDIT: when I call su -c "id" programatically, there's output that uid=0.

Answer

LoneDuck picture LoneDuck · Apr 20, 2015

I can get stuck on a problem for days, and the moment I gather up the courage to ask about it on StackOverflow, it is solved within minutes.

The fix is:

    p=Runtime.getRuntime().exec("su");
    DataOutputStream dos = new DataOutputStream(p.getOutputStream());
    dos.writeBytes("mkdir /sdcard/testdir\n");
    dos.writeBytes("exit\n");
    dos.flush();
    dos.close();
    p.waitFor();

Don't forget \n at the end of each command you write to the DataOutputStream, as it will not work without it.