Running Shell Commands Though Java Code on Android

Running Shell commands though java code on Android?

To run root commands, you have to use the flllowing format:

    public void RunAsRoot(String[] cmds){
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
}
os.writeBytes("exit\n");
os.flush();
}

where you pass in an array of strings, each string being a command that needs to be executed. For example:

String[] commands = {"sysrw", "rm /data/local/bootanimation.zip", "sysro"};

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
outputStream.flush();

outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}catch(IOException e){
throw new Exception(e);
}catch(InterruptedException e){
throw new Exception(e);
}

Running Android shell command from Java code returns empty output

I partially found my answer which is sufficient enough. Basically problem was with permissions as suspected in the first place.

As stated in documentation: from Android version 10 /proc/net filesystem is restricted and can not be accessed. Unlucky (or should I say lucky) thing was that my non-rooted test device is Android 10 and therefore process object would have returned status 1 because it had no permission to read /proc/net filesystem.

I tested the same code on Android 8 and everything worked as expected.

I still haven't figured out how to access used ports, but I'll look into NetworkStatsManager and ConnectivityManager classes as noted in previously linked documentation.

Run adb shell commands from Java code on different platforms

Better use ProcessBuilder instead. But if you insist on using Runtime.getRuntime().exec() - use .exec(String[] cmdarray) instead of your current .exec(String command):

private static final String DUMPSYSCOMMAND = "dumpsys package com.PACKAGENAME.service | grep versionName";

String versionString = runADBCommand({"adb", "-s", deviceIP, "shell", DUMPSYSCOMMAND});

...

public String runADBCommand(String[] adbCommand) throws IOException {

...

// do not forget to remove / modify this println - it expect a string
// System.out.println("adbCommand = " + adbCommand);

How to run cmd/shell commands from android studio programmatically?

You can't execute ADB directly from an android device.

You'll need to write a desktop application which executes the command and can be called by the android application, or (easier) use an automation software to call remote commands from your phone.



Related Topics



Leave a reply



Submit