Executing Shell Commands from Android via Java
In this inquiry, the user attempts to execute the "screenrecord" command from within a Java application on an Android device. However, unlike its successful execution from the terminal emulator, the same code fails from Java.
Solution
The problem stems from the insufficient permissions accorded to the Java process. To rectify this, one must first attain superuser privileges by executing "su" and then relay the "screenrecord" command through the standard input of the initiated "su" process.
The following Java code offers a solution:
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 | InterruptedException e) { throw new Exception(e); }
This modified code acquires the standard input of the "su" process, transmits the "screenrecord" command, and terminates the "su" process, allowing the command to execute with the necessary elevated privileges.
The above is the detailed content of How to Execute Shell Commands like 'screenrecord' from Java on Android?. For more information, please follow other related articles on the PHP Chinese website!