Saturday, November 16, 2013

Running ADB shell commands within uiautomator


Running ADB shell commands within uiautomator

ADB Input Keyevents:


While running UI automation tests we would love to set up our prerequisites for the test with as much little UI interaction as possible. This will ensure that the tests would not get blocked due to failures in the prerequisites.

For instance, you can go to the home of your phone/tablet/emulator with a simple adb shell command:
adb shell input keyevent KEYCODE_HOME (or)
adb shell input keyevent 3

For more details about input key events you can look into this link,
http://developer.android.com/reference/android/view/KeyEvent.html

Implementation with uiautomator:

The usage of the above adb shell commands can be implemented by using exec() property which executes the specified command and arguments in a separate process.
The output of the command is then read by using an Buffered reader.

Code Snippet:


public String runADBCommand(String adbCommand) throws IOException {
  String returnValue = "", line;
  InputStream inStream = null;
  try {
    Process process = Runtime.getRuntime().exec(adbCommand);
    inStream = process.getInputStream();
    BufferedReader brCleanUp = new BufferedReader(
                                               new InputStreamReader(inStream));
    while ((line = brCleanUp.readLine()) != null) {
         returnValue = returnValue + line + "\n";
    }
    brCleanUp.close();
    try {
         process.waitFor();
    } catch (InterruptedException e) {
         e.printStackTrace();
    }
  } catch (Exception e) {
    e.printStackTrace();
    System.err.println("Error: " + e.getMessage());
  }
  System.out.println(returnValue);
  return returnValue;
 }