How to execute a shell command from android app

  Uncategorized

To execute a shell command from your android app you can grab the standard input of the su process just launched by Runtime.getRuntime().exec(“su”) and write down the command there, otherwise you are running the commands with the current UID.

With the following code you can excute the screenrecord command to grab your screen to a mp4 video file (Works on Android 4.4 API level 19 and higher). There are many othe commands you can execute. You can find some of them at https://developer.android.com/tools/help/shell.html

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);
}

Source:
http://stackoverflow.com/questions/20932102/execute-shell-command-from-android