java.lang.Object
com.pnfsoftware.jeb.core.units.code.android.adb.AdbWrapper

public class AdbWrapper extends Object
A controller for the Android Debug Bridge (ADB) tool. Remember to call initialize() if necessary (e.g., first adb run). Most methods in this class return null on error.

This class contains several helpful utility methods; if what you're looking for is not here, use execute or executeOn as a last resort. More complex and/or smarter wrapper functions can also be found in the AndroidDeviceUtil class.

This class is thread-safe; the object itself may be used in synchronized blocks for transactions.

TODO: use ProcessWrapper

  • Field Details

    • STANDARD_TIMEOUT

      public static final long STANDARD_TIMEOUT
      Standard command execution timeout is 5 seconds.
      See Also:
  • Method Details

    • initialize

      public boolean initialize()
      Initialize the wrapper and wait for a device.
      Returns:
      true if initialization succeeded
    • getPath

      public String getPath()
      Get the path to the ADB binary wrapped by this object.
      Returns:
      ADB binary path
    • setTargetDevice

      public void setTargetDevice(String deviceSerial)
      Set the default target device for operations.
      Parameters:
      deviceSerial - the serial number (the case matters)
    • getTargetDevice

      public String getTargetDevice()
      Get the default target device for operations. The result may be null, in which case, adb will work if and only if a single device is connected (and that device will be used for operations).
      Returns:
      the serial number (the case matters); may be null if no target was explicitly specified
    • setRunAs

      public void setRunAs(String path)
      Set the run-as command path.
      Parameters:
      path - run-as path, or null to disable run-as wrapping
    • getRunAs

      public String getRunAs()
      Retrieve the run-as command path.
      Returns:
      run-as path, or null
    • setToolName

      public void setToolName(String standardName, String alternateName)
      Register an alternate command name for a standard Android tool.
      Parameters:
      standardName - standard command name
      alternateName - alternate command name
    • getToolName

      public String getToolName(String name)
      Retrieve the configured command name for a standard Android tool.
      Parameters:
      name - standard command name
      Returns:
      configured command name
    • setDefaultTimeout

      public void setDefaultTimeout(long millis)
      Set the default command timeout.
      Parameters:
      millis - timeout in milliseconds; 0 means infinite
    • getDefaultTimeout

      public long getDefaultTimeout()
      Retrieve the default command timeout.
      Returns:
      timeout in milliseconds; 0 means infinite
    • getVersion

      public String getVersion()
      Get the adb tool version used by this wrapper.
      Returns:
      ADB version, or null on error
    • startServer

      public boolean startServer()
      Start the ADB server (on the local machine).
      Returns:
      true on success
    • stopServer

      public void stopServer()
      Stop the ADB server.
    • listDevices

      public List<AdbDevice> listDevices()
      List devices known to ADB.
      Returns:
      device list, or null on error
    • logcat

      public ProcessWrapper logcat() throws IOException
      Execute the logcat command.
      Returns:
      the process wrapper
      Throws:
      IOException - on error
    • logcat

      public ProcessWrapper logcat(Integer pid, String afterDate) throws IOException
      Execute the logcat command with filter options.
      Parameters:
      pid - (optional) only the logs issued by the specified process
      afterDate - (optional) cut-off date: only logs generated after the provided date are output; format must be like YYYY-mm-dd HH:MM:SS.xxx
      Returns:
      the process wrapper
      Throws:
      IOException - on error
    • logcatClear

      public boolean logcatClear()
      Clear the device logcat buffer.
      Returns:
      true on success
    • waitForDevice

      public boolean waitForDevice()
      adb wait-for-device command. Uses a 30 second time-out.
      Returns:
      true on success
    • waitForBootCompletionHeur1

      public boolean waitForBootCompletionHeur1()
      Uses dev.bootcomplete property. Uses a 30 second time-out.

      Does not seem reliable.

      Returns:
      true if boot completion was detected
    • waitForBootCompletionHeur2

      public boolean waitForBootCompletionHeur2()
      Uses init.svc.bootanim property. Uses a 30 second time-out.

      Does not seem reliable.

      Returns:
      true if boot completion was detected
    • waitForBootCompletionHeur3

      public boolean waitForBootCompletionHeur3()
      Uses the Package Manager to find out whether the system is ready for app installation. Uses a 30 second time-out.

      Flaky heuristic (Jenkins only), b/c reading 'init.svc.bootanim' does not seem to do the trick on my slow emulator.

      Returns:
      true if boot completion was detected
    • installApp

      public boolean installApp(String apkPath)
      Install an APK.
      Parameters:
      apkPath - APK path
      Returns:
      true on success
    • installAppForce

      public boolean installAppForce(String apkPath)
      Install or replace an APK.
      Parameters:
      apkPath - APK path
      Returns:
      true on success
    • installApp

      public boolean installApp(String apkPath, boolean allowReplace, boolean onSdcard, boolean grantRuntimePermissions)
      Install an APK.
      Parameters:
      apkPath - APK path
      allowReplace - true to allow replacement
      onSdcard - true to install on external storage
      grantRuntimePermissions - true to grant runtime permissions on install when supported
      Returns:
      true on success
    • uninstallApp

      public boolean uninstallApp(String packageName)
      Uninstall an APK.
      Parameters:
      packageName - package name
      Returns:
      true on success
    • uninstallApp

      public boolean uninstallApp(String packageName, boolean keepData)
      Uninstall an APK.
      Parameters:
      packageName - package name
      keepData - true to keep application data
      Returns:
      true on success
    • pushFile

      public boolean pushFile(String localPath, String remotePath)
      Upload a file onto a device.
      Parameters:
      localPath - local source path
      remotePath - device destination path
      Returns:
      true on success
    • pullFile

      public boolean pullFile(String remotePath, String localPath)
      Download a file from a device.
      Parameters:
      remotePath - device source path
      localPath - local destination path
      Returns:
      true on success
    • listJdwpPids

      public List<Integer> listJdwpPids()
      List the PIDs of processes hosting a JDWP transport. Use a timeout of 1 second.
      Returns:
      a list of process ids
    • forwardJdwpToTcp

      public boolean forwardJdwpToTcp(int srcJdwpPid, int dstTcpPort)
      Forward a JDWP endpoint to a local TCP port.
      Parameters:
      srcJdwpPid - JDWP process id
      dstTcpPort - destination TCP port
      Returns:
      true on success
    • forwardLocalToTcp

      public boolean forwardLocalToTcp(String srcDomainSocket, int dstTcpPort)
      Forward a local filesystem socket to a local TCP port.
      Parameters:
      srcDomainSocket - source domain socket path
      dstTcpPort - destination TCP port
      Returns:
      true on success
    • forwardToTcp

      public boolean forwardToTcp(AdbForwardType srcType, String srcDomainSocket, int dstTcpPort)
      Forward a device endpoint to a local TCP port.
      Parameters:
      srcType - source endpoint type
      srcDomainSocket - source endpoint name or path
      dstTcpPort - destination TCP port
      Returns:
      true on success
    • stopForwardToTcp

      public boolean stopForwardToTcp(int dstTcpPort)
      Issue a adb forward --remove tcp:port command.
      Parameters:
      dstTcpPort - destination TCP port
      Returns:
      true on success
    • stopAllForwards

      public boolean stopAllForwards(int dstTcpPort)
      Remove all ADB forwards.
      Parameters:
      dstTcpPort - ignored
      Returns:
      true on success
    • readProperty

      public String readProperty(String propertyName)
      Read a device Android property.
      Parameters:
      propertyName - property fully-qualified name
      Returns:
      property value, or null on error
    • listProcesses

      public List<AdbProcess> listProcesses()
      List the processes running on this device.
      Returns:
      process list, or null on error
    • listPackages

      public List<AdbPackage> listPackages()
      List installed packages.
      Returns:
      package list, or null on error
    • listPackages

      public List<AdbPackage> listPackages(AdbPackageManagerOptions options)
      List installed packages.
      Parameters:
      options - package-manager options, or null
      Returns:
      package list, or null on error
    • startActivity

      public boolean startActivity(String pname, String aname, boolean bEnableDebugging, boolean bWaitForLaunch, boolean bForceStopBeforeStart)
      Start an activity. Uses the Activity Manager (am) internally. Example: adb shell am start -n com.xyz.appcheck/.AppCheck
      Parameters:
      pname - package name
      aname - activity name
      bEnableDebugging - will wait for debugger to connect. If true, bForceStopBeforeStart is disregarded; also not recommended to set bWaitForLaunch to true, as am would not return until a debugger connects
      bWaitForLaunch - wait for activity to have launched before 'am' returns
      bForceStopBeforeStart - the already running activity, if there is one, will be killed (instead of simply be brought up to the front)
      Returns:
      true on success
    • startActivity

      public boolean startActivity(String pname, String aname)
      Start an activity.
      Parameters:
      pname - package name
      aname - activity name
      Returns:
      true on success
    • stopApp

      public boolean stopApp(String pname)
      Force-stop an application.
      Parameters:
      pname - package name
      Returns:
      true on success
    • killProcess

      public void killProcess(String user, int pid)
      Send the TERM signal to request normal termination of a process.
      Parameters:
      user - optional run-as user
      pid - process id
    • stopProcess

      public boolean stopProcess(String user, int pid)
      Send the STOP signal to a process.
      Parameters:
      user - optional run-as user
      pid - process id
      Returns:
      true if one of the signal names was accepted
    • killProcess

      public void killProcess(String user, int pid, int signal)
      Send a signal to a process.
      Parameters:
      user - optional run-as user
      pid - process id
      signal - signal number
    • killProcess

      public boolean killProcess(String user, int pid, String... signalNames)
      Send a signal to a process.
      Parameters:
      user - optional run-as user
      pid - process id
      signalNames - candidate signal names
      Returns:
      true if one of the signals was accepted
    • hasFile

      public boolean hasFile(String user, String path)
      Verify if a file is present.
      Parameters:
      user - optional run-as user
      path - full exact path, no wildcard
      Returns:
      true if the file exists
    • touchFile

      public boolean touchFile(String user, String path)
      Create an empty file.
      Parameters:
      user - optional run-as user
      path - path to create
      Returns:
      false indicates sure failure; true indicates potential success (not guaranteed; use hasFile(String, String) to confirm)
    • deleteFile

      public boolean deleteFile(String user, String path, boolean recurse)
      Delete a file or folder.
      Parameters:
      user - optional run-as user
      path - path to delete
      recurse - true to delete recursively
      Returns:
      true on success
    • copyFile

      public boolean copyFile(String user, String srcPath, String dstPath, boolean recurse)
      Copy a file or folder.
      Parameters:
      user - optional run-as user
      srcPath - source path
      dstPath - destination path
      recurse - true to copy recursively
      Returns:
      true on success
    • chmod

      public boolean chmod(String user, String path, int perm, boolean recurse)
      Change the permissions of a file or folder.
      Parameters:
      user - optional run-as user
      path - path to modify
      perm - octal permission bits
      recurse - true to apply recursively
      Returns:
      true on success
    • chown

      public boolean chown(String user, String path, String userName, String groupName, boolean recurse)
      Change the ownership of a file or folder.
      Parameters:
      user - optional run-as user
      path - path to modify
      userName - mandatory
      groupName - optional
      recurse - true to apply recursively
      Returns:
      true on success
    • which

      public String which(String user, String path)
      Find the location of a binary file.
      Parameters:
      user - optional run-as user
      path - binary name
      Returns:
      resolved path, or null on error
    • dateEpoch

      public long dateEpoch()
      Retrieve the device date in seconds since 1970-01-01 00:00:00 UTC.
      Returns:
      -1 on error, else the Unix timestamp
    • dateString

      public String dateString(boolean appendTimezoneDelta)
      Retrieve the device date in the following format: YYYY-mm-dd_HH:MM:SS or YYYY-mm-dd_HH:MM:SS_TZD where TZD is like "+/-HHMM"

      Examples: "2016-01-16_12:32:44", 2016-01-16_12:32:44_-0500

      Parameters:
      appendTimezoneDelta - append time zone delta information
      Returns:
      the date string
    • shellLog

      public AdbResult shellLog(String user, List<String> arguments)
      Execute a shell command and log its output.
      Parameters:
      user - optional run-as user
      arguments - shell command arguments
      Returns:
      ADB result
    • shell

      public AdbResult shell(String user, List<String> arguments)
      Execute a shell command.
      Parameters:
      user - optional run-as user
      arguments - shell command arguments
      Returns:
      ADB result
    • shell

      public AdbResult shell(Long timeout, String deviceSerial, String user, List<String> arguments)
      Execute a shell command.
      Parameters:
      timeout - optional timeout in milliseconds
      deviceSerial - optional target device serial
      user - optional run-as user
      arguments - shell command arguments
      Returns:
      ADB result
    • shell

      public AdbResult shell(List<String> arguments)
      Execute a shell command on the default target.
      Parameters:
      arguments - shell command arguments
      Returns:
      ADB result
    • shell

      public AdbResult shell(Long timeout, String deviceSerial, String user, List<String> arguments, boolean logOnResult)
      Execute a shell command.
      Parameters:
      timeout - optional timeout in milliseconds
      deviceSerial - optional target device serial
      user - optional run-as user
      arguments - shell command arguments
      logOnResult - true to log command output
      Returns:
      ADB result
    • executeOn

      public byte[] executeOn(Long timeout, String deviceSerial, Collection<String> arguments)
      Execute a command using ADB. Do not provide "-s ..." manually, use the appropriate argument instead.
      Parameters:
      timeout - null to use a default timeout
      deviceSerial - optional, leave null to let ADB decide on which device the command should be executed
      arguments - ADB arguments
      Returns:
      command output bytes, or null on error
    • execute

      public byte[] execute(Long timeout, Collection<String> arguments)
      Execute a command using ADB. This method may block indefinitely, for some time, or return immediately.
      Parameters:
      timeout - null to use the default timeout; else, refer to ProcessExec for timeout meaning
      arguments - ADB arguments
      Returns:
      command output bytes, or null on error
    • executeAsync

      public ProcessWrapper executeAsync(Long timeout, boolean redirectErrToOut, Collection<String> arguments) throws IOException
      Advanced method used to execute an ADB command with as much flexibility as needed. This method is non-blocking.
      Parameters:
      timeout - timeout in ms (use -1 to specify no timeout; use null to use the default timeout)
      redirectErrToOut - true to redirect stderr to stdout
      arguments - adb arguments
      Returns:
      a process wrapper object; null on error
      Throws:
      IOException - on error
    • shellAsync

      public ProcessWrapper shellAsync(Long timeout, String deviceSerial, String user, List<String> arguments) throws IOException
      Advanced method used to execute a shell ADB command. This method is non-blocking.
      Parameters:
      timeout - timeout in ms (use -1 to specify no timeout; use null to use the default timeout)
      deviceSerial - optional target device
      user - optional user
      arguments - adb arguments
      Returns:
      a process wrapper object; null on error
      Throws:
      IOException - on error
    • toString

      public String toString()
      Overrides:
      toString in class Object