1

I need to run adb commands programmatically on rooted android device.

The following is not working, no exception just not working:

Process process = Runtime.getRuntime().exec(command);
process.waitFor();

Also, if I want to run command as a specific user role, how do I execute it?

0

2 Answers 2

4

You can use this:

Process p = Runtime.getRuntime().exec( "su" );
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes(command1 + "\n");
os.writeBytes(command2 + "\n");
os.writeBytes("exit\n");
os.flush();

As your device is rooted you must use su command to use commands for rooted devices. I used this solution for restarting our rooted devices from our app and it worked. You can add multiple commands as you see in the code. Hope it works.

Update:

You can use array of commands too. Like this:

Process proc = Runtime.getRuntime()
              .exec(new String[] { "su", "-c", command1,command2,"exit" });
proc.waitFor();

or you can use extra exec commands if you need it:

Runtime runtime = Runtime.getRuntime();
runtime.exec("su");
runtime.exec("export LD_LIBRARY_PATH=/vendor/lib:/system");
runtime.exec("pm clear "+PACKAGE_NAME);

This samples will work too, I used them before.

6
  • Please provide a short description about what this block of code does. Commented Mar 13, 2018 at 8:40
  • @KeivanEsbati thanks for reminding. I edited the post.
    – ckaraboran
    Commented Mar 13, 2018 at 8:57
  • do you not need to execute this process like p.exec(); ? Commented Mar 13, 2018 at 9:57
  • @pratiti-systematix No need. When you use su command with exec, shell will become the process. So it will accept all new commands. But I added another samples for different situations.
    – ckaraboran
    Commented Mar 13, 2018 at 11:09
  • 1
    @ckaraboran, i tried as you guide, I'm getting this error can you please check Cannot run program "su": error=13, Permission denied I need to execute ADB shell commands in Android Application. LMK your suggestions.
    – m9m9m
    Commented May 22, 2018 at 13:16
3

I would like to answer your questions second part, that is how to run a command as a specific user role ? for this you can use the following Linux Command which is inbuilt in android.

run-as : Usage:
    run-as <package-name> [--user <uid>] <command> [<args>]

As Example

run-as com.example.root.app --user u0_a86 env 

Not the answer you're looking for? Browse other questions tagged or ask your own question.