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?

pratiti-systematix
  • 792
  • 11
  • 28

2 Answers2

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.

ckaraboran
  • 41
  • 1
  • 4
  • Please provide a short description about what this block of code does. – Keivan Esbati Mar 13 '18 at 08:40
  • @KeivanEsbati thanks for reminding. I edited the post. – ckaraboran Mar 13 '18 at 08:57
  • do you not need to execute this process like p.exec(); ? – pratiti-systematix Mar 13 '18 at 09: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 Mar 13 '18 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 May 22 '18 at 13:16
  • @m9m9m Are you sure that your device is a rooted device? If it is not rooted you can't use "su" command. But other commands will work. – ckaraboran May 22 '18 at 13:45
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 
Shahbaz Ali
  • 1,262
  • 1
  • 12
  • 13