Skip to content

How To Automate Screen Recording In Appium

Why do we need to automate screen recording in Appium? Most of the time, while doing test suite execution, a few tests fail, and to debug that, we need to check the logs or screenshots first. What if we get the recording of failed tests and by going through these we can identify at what step the test case failed, was it because of locator change, due to network issue, or any other issue?

Platforms like SauceLabs and BrowserStack use video recording APIs to provide the recordings of the execution result.

How To Use ScreenRecorder

Add the below dependency in the pom.xml file under <dependencies></dependencies> tag.

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

The Apache Commons Codec package contains simple encoders and decoders for various formats such as Base64 and Hexadecimal.

Add below static imports in the class

import io.appium.java_client.screenrecording.CanRecordScreen;
import org.apache.commons.codec.binary.Base64;

Create a class and add the below methods

1)Create a method named StartRecording()

public void startRecording()
 {
        ((CanRecordScreen)webDriver).startRecordingScreen();
 }

CanRecordScreen is an interface that extends another interface ExecutesMethod. This interface has the method startRecordingScreen() that Starts the asynchronous screen recording process with default options.

2)Create a method StopRecording()

Tasks:

2.1)Recorded Base64 encoded content and stored it in String format.
2.2)Define the path to store the recorded video.
2.3)Open a FileOutputStream
2.4)Store the recorded media in mp4 format.
2.5)Add a timestamp with the videos.
2.6)Write and close the Output Stream.

private static String timestamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()).replaceAll(":", "-");
String media = ((CanRecordScreen) webDriver).stopRecordingScreen();
String dirPath =   System.getProperty("user.dir")+"/Videos";
  
   File videoDir = new File(dirPath);
   FileOutputStream stream = null;
try {
 stream = new FileOutputStream(videoDir + File.separator +timestamp+ ".mp4");
            stream.write(Base64.decodeBase64(media));
            stream.close();
            
        } catch (Exception e) {
            
        } finally {
            if(stream != null) {
                stream.close();
            }
        }

In the above script, we passed the web driver object and called the stopRecordingScreen() method. This method Gathers the output from the previously started screen recording to a media file with default options and Returns: The base-64 encoded content of the recorded media file.

Complete Code

Refer to the code snippet for the full working code

public class AndroidRunner {
    public AndroidDriver<MobileElement> wd = null;
    static AppiumDriverLocalService service;
    private static String timestamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()).replaceAll(":", "-");


    @BeforeSuite
    public void startappium()
     {
        service = AppiumDriverLocalService.buildDefaultService();
        service.start();
     }


  @BeforeTest
  public void setup() {
     DesiredCapabilities capabilities = new DesiredCapabilities();
     capabilities.setCapability("platformName", "Android");
     capabilities.setCapability("appPackage", "com.walkwithme");
     capabilities.setCapability("appActivity", "walkwithme.MainActivity");
     capabilities.setCapability("deviceName", "Android");
     capabilities.setCapability("app",System.getProperty("user.dir")+"PathToApk");

 try {
 wd = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);
    startRecording();
     }catch(Exception e) {
       e.printStackTrace();
      }
    }
    
    public void startRecording() throws MalformedURLException {
        ((CanRecordScreen)wd).startRecordingScreen();
    }
    
    public void stopRecording() throws IOException {

       String media = ((CanRecordScreen) wd).stopRecordingScreen();
       String dirPath =   System.getProperty("user.dir")+"/Videos";
       File videoDir = new File(dirPath);
       FileOutputStream stream = null;
       
    try {
      stream = new FileOutputStream(videoDir + File.separator +timestamp+ ".mp4");
            stream.write(Base64.decodeBase64(media));
            stream.close();

        } catch (Exception e) {

        } finally {
            if(stream != null) {
                stream.close();
            }
        }
    }

    @Test
    public void applicationrunb() throws Throwable {
      System.out.println("HELLO App launched");
     wd.findElementByClassName("android.widget.EditText").sendKeys("hello");
     }

    @AfterTest
    public void stopappium() throws IOException {
        stopRecording();
        wd.quit();
    }

    @AfterSuite
    public void closeservice() {
        service.stop();
    }
}

Now Execute the Script, Refresh and check the videos folder. MP4 file should be there.

Enable Screen Recording In Appium