Home > Java > javaTutorial > How to Execute Shell Commands like 'screenrecord' from Java on Android?

How to Execute Shell Commands like 'screenrecord' from Java on Android?

Linda Hamilton
Release: 2024-11-10 06:01:02
Original
735 people have browsed it

How to Execute Shell Commands like

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template