pratiti-systematix
pratiti-systematix

Reputation: 812

How to run ADB command programmatically on rooted android device

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?

Upvotes: 1

Views: 7491

Answers (2)

Shahbaz Ali
Shahbaz Ali

Reputation: 1410

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 

Upvotes: 3

ckaraboran
ckaraboran

Reputation: 41

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.

Upvotes: 4

Related Questions