Home >Java >javaTutorial >Why Does Executing 'su' Commands Differently in Java and Emulator Terminals?
Executing Shell Commands from Android: An Analysis of a Common Pitfall
In Android development, there may arise instances where executing shell commands is necessary. However, common pitfalls can occur when attempting to execute such commands from within a Java application. One such pitfall is observed with the "su" command which grants superuser privileges in rooted devices.
Consider the scenario of screen capturing using the screenrecord command. When executed through the application emulator terminal, the command successfully initiates the recording. However, executing the same command from Java using the Runtime.getRuntime().exec() method fails to create the recording.
The discrepancy arises from the method of passing commands to the "su" process. The emulator terminal allows for direct entry of commands, while in Java, the command must be provided as input to the "su" process through its standard input.
The solution involves redirecting the command to the "su" process's standard input using DataOutputStream. Here's the revised code snippet:
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); }
By redirecting the command to the standard input, the "su" process receives the command and elevates it with root privileges, successfully executing the screen recording. This technique ensures that shell commands can be effectively executed from Android applications, even requiring superuser privileges.
The above is the detailed content of Why Does Executing 'su' Commands Differently in Java and Emulator Terminals?. For more information, please follow other related articles on the PHP Chinese website!