Search code examples
javaandroidmultithreadingadbthreadpoolexecutor

How to can I run adb screenrecord on a Android Device from Java and end the screenrecording?


How to can I run adb shell screenrecord on a Android Device from Java and end the screenrecording?

Currently I have to specify the --time-limit to end the recording. If I try to capture the video prior to it ending it fails.

Is there a way to tell adb to stop recording? Is there a way to configure the thread to send a CTRL-C to the shell command?

This is to be run on unrooted phones.

Code

videoExecutor.submit(() -> {
          //Start recording video
        String recordVideo = "screenrecord --time-limit " + testRun.getVideoLength() + " " + "/sdcard/" + logDate + ".mp4";
    try {
      device.executeShell(recordVideo);
  } catch (Exception e1) {
    e1.printStackTrace();
  }
    sleep(testRun.getVideoLength()*ONE_SECOND + TWO_SECONDS);  //gotta match the --time-limit above.

RemoteFile remote = new RemoteFile("/sdcard/" + logDate + ".mp4");
File local = new File(videoPath); //Save file to local machine
          if(!local.getParentFile().exists()) {
              local.getParentFile().mkdirs();
          }

    try {
      //Copy video from phone to computer
        try {
                  device.pull(remote, local);
              } catch (Exception e) {
                  e.printStackTrace();
              }
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

      });

Solution

  • Sending either SIGINT or SIGHUP to screenrecord process would cause it to stop recording.

    I just tried the following on unrooted (stock Android 6.0) phone in 2 separate adb shell sessions:

    in session #1:

    screenrecord /sdcard/Movies/test.mpg
    

    in session #2:

    pkill -INT screenrecord
    

    and the screenrecord capture stopped after issuing the pkill command