Class AdbWrapper
java.lang.Object
com.pnfsoftware.jeb.core.units.code.android.adb.AdbWrapper
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 Summary
FieldsModifier and TypeFieldDescriptionstatic final longStandard command execution timeout is 5 seconds. -
Method Summary
Modifier and TypeMethodDescriptionbooleanChange the permissions of a file or folder.booleanChange the ownership of a file or folder.booleanCopy a file or folder.longRetrieve the device date in seconds since 1970-01-01 00:00:00 UTC.dateString(boolean appendTimezoneDelta) Retrieve the device date in the following format:YYYY-mm-dd_HH:MM:SSorYYYY-mm-dd_HH:MM:SS_TZDwhere TZD is like "+/-HHMM"booleandeleteFile(String user, String path, boolean recurse) Delete a file or folder.byte[]execute(Long timeout, Collection<String> arguments) Execute a command using ADB.executeAsync(Long timeout, boolean redirectErrToOut, Collection<String> arguments) Advanced method used to execute an ADB command with as much flexibility as needed.byte[]executeOn(Long timeout, String deviceSerial, Collection<String> arguments) Execute a command using ADB.booleanforwardJdwpToTcp(int srcJdwpPid, int dstTcpPort) Forward a JDWP endpoint to a local TCP port.booleanforwardLocalToTcp(String srcDomainSocket, int dstTcpPort) Forward a local filesystem socket to a local TCP port.booleanforwardToTcp(AdbForwardType srcType, String srcDomainSocket, int dstTcpPort) Forward a device endpoint to a local TCP port.longRetrieve the default command timeout.getPath()Get the path to the ADB binary wrapped by this object.getRunAs()Retrieve therun-ascommand path.Get the default target device for operations.getToolName(String name) Retrieve the configured command name for a standard Android tool.Get the adb tool version used by this wrapper.booleanVerify if a file is present.booleanInitialize the wrapper and wait for a device.booleaninstallApp(String apkPath) Install an APK.booleaninstallApp(String apkPath, boolean allowReplace, boolean onSdcard, boolean grantRuntimePermissions) Install an APK.booleaninstallAppForce(String apkPath) Install or replace an APK.voidkillProcess(String user, int pid) Send the TERM signal to request normal termination of a process.voidkillProcess(String user, int pid, int signal) Send a signal to a process.booleankillProcess(String user, int pid, String... signalNames) Send a signal to a process.List devices known to ADB.List the PIDs of processes hosting a JDWP transport.List installed packages.listPackages(AdbPackageManagerOptions options) List installed packages.List the processes running on this device.logcat()Execute thelogcatcommand.Execute thelogcatcommand with filter options.booleanClear the device logcat buffer.booleanDownload a file from a device.booleanUpload a file onto a device.readProperty(String propertyName) Read a device Android property.voidsetDefaultTimeout(long millis) Set the default command timeout.voidSet therun-ascommand path.voidsetTargetDevice(String deviceSerial) Set the default target device for operations.voidsetToolName(String standardName, String alternateName) Register an alternate command name for a standard Android tool.Execute a shell command.Execute a shell command.Execute a shell command.Execute a shell command on the default target.Advanced method used to execute a shell ADB command.Execute a shell command and log its output.booleanstartActivity(String pname, String aname) Start an activity.booleanstartActivity(String pname, String aname, boolean bEnableDebugging, boolean bWaitForLaunch, boolean bForceStopBeforeStart) Start an activity.booleanStart the ADB server (on the local machine).booleanstopAllForwards(int dstTcpPort) Remove all ADB forwards.booleanForce-stop an application.booleanstopForwardToTcp(int dstTcpPort) Issue aadb forward --remove tcp:portcommand.booleanstopProcess(String user, int pid) Send the STOP signal to a process.voidStop the ADB server.toString()booleanCreate an empty file.booleanuninstallApp(String packageName) Uninstall an APK.booleanuninstallApp(String packageName, boolean keepData) Uninstall an APK.booleanUsesdev.bootcompleteproperty.booleanUsesinit.svc.bootanimproperty.booleanUses the Package Manager to find out whether the system is ready for app installation.booleanadb wait-for-devicecommand.Find the location of a binary file.
-
Field Details
-
STANDARD_TIMEOUT
public static final long STANDARD_TIMEOUTStandard 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
Get the path to the ADB binary wrapped by this object.- Returns:
- ADB binary path
-
setTargetDevice
Set the default target device for operations.- Parameters:
deviceSerial- the serial number (the case matters)
-
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
Set therun-ascommand path.- Parameters:
path-run-aspath, or null to disable run-as wrapping
-
getRunAs
Retrieve therun-ascommand path.- Returns:
run-aspath, or null
-
setToolName
Register an alternate command name for a standard Android tool.- Parameters:
standardName- standard command namealternateName- alternate command name
-
getToolName
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
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
List devices known to ADB.- Returns:
- device list, or null on error
-
logcat
Execute thelogcatcommand.- Returns:
- the process wrapper
- Throws:
IOException- on error
-
logcat
Execute thelogcatcommand with filter options.- Parameters:
pid- (optional) only the logs issued by the specified processafterDate- (optional) cut-off date: only logs generated after the provided date are output; format must be likeYYYY-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-devicecommand. Uses a 30 second time-out.- Returns:
- true on success
-
waitForBootCompletionHeur1
public boolean waitForBootCompletionHeur1()Usesdev.bootcompleteproperty. Uses a 30 second time-out.Does not seem reliable.
- Returns:
- true if boot completion was detected
-
waitForBootCompletionHeur2
public boolean waitForBootCompletionHeur2()Usesinit.svc.bootanimproperty. 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
Install an APK.- Parameters:
apkPath- APK path- Returns:
- true on success
-
installAppForce
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 pathallowReplace- true to allow replacementonSdcard- true to install on external storagegrantRuntimePermissions- true to grant runtime permissions on install when supported- Returns:
- true on success
-
uninstallApp
Uninstall an APK.- Parameters:
packageName- package name- Returns:
- true on success
-
uninstallApp
Uninstall an APK.- Parameters:
packageName- package namekeepData- true to keep application data- Returns:
- true on success
-
pushFile
Upload a file onto a device.- Parameters:
localPath- local source pathremotePath- device destination path- Returns:
- true on success
-
pullFile
Download a file from a device.- Parameters:
remotePath- device source pathlocalPath- local destination path- Returns:
- true on success
-
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 iddstTcpPort- destination TCP port- Returns:
- true on success
-
forwardLocalToTcp
Forward a local filesystem socket to a local TCP port.- Parameters:
srcDomainSocket- source domain socket pathdstTcpPort- destination TCP port- Returns:
- true on success
-
forwardToTcp
Forward a device endpoint to a local TCP port.- Parameters:
srcType- source endpoint typesrcDomainSocket- source endpoint name or pathdstTcpPort- destination TCP port- Returns:
- true on success
-
stopForwardToTcp
public boolean stopForwardToTcp(int dstTcpPort) Issue aadb forward --remove tcp:portcommand.- 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
Read a device Android property.- Parameters:
propertyName- property fully-qualified name- Returns:
- property value, or null on error
-
listProcesses
List the processes running on this device.- Returns:
- process list, or null on error
-
listPackages
List installed packages.- Returns:
- package list, or null on error
-
listPackages
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 nameaname- activity namebEnableDebugging- 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 connectsbWaitForLaunch- wait for activity to have launched before 'am' returnsbForceStopBeforeStart- 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
Start an activity.- Parameters:
pname- package nameaname- activity name- Returns:
- true on success
-
stopApp
Force-stop an application.- Parameters:
pname- package name- Returns:
- true on success
-
killProcess
Send the TERM signal to request normal termination of a process.- Parameters:
user- optional run-as userpid- process id
-
stopProcess
Send the STOP signal to a process.- Parameters:
user- optional run-as userpid- process id- Returns:
- true if one of the signal names was accepted
-
killProcess
Send a signal to a process.- Parameters:
user- optional run-as userpid- process idsignal- signal number
-
killProcess
Send a signal to a process.- Parameters:
user- optional run-as userpid- process idsignalNames- candidate signal names- Returns:
- true if one of the signals was accepted
-
hasFile
Verify if a file is present.- Parameters:
user- optional run-as userpath- full exact path, no wildcard- Returns:
- true if the file exists
-
touchFile
Create an empty file.- Parameters:
user- optional run-as userpath- path to create- Returns:
- false indicates sure failure; true indicates potential success (not guaranteed; use
hasFile(String, String)to confirm)
-
deleteFile
Delete a file or folder.- Parameters:
user- optional run-as userpath- path to deleterecurse- true to delete recursively- Returns:
- true on success
-
copyFile
Copy a file or folder.- Parameters:
user- optional run-as usersrcPath- source pathdstPath- destination pathrecurse- true to copy recursively- Returns:
- true on success
-
chmod
Change the permissions of a file or folder.- Parameters:
user- optional run-as userpath- path to modifyperm- octal permission bitsrecurse- true to apply recursively- Returns:
- true on success
-
chown
Change the ownership of a file or folder.- Parameters:
user- optional run-as userpath- path to modifyuserName- mandatorygroupName- optionalrecurse- true to apply recursively- Returns:
- true on success
-
which
Find the location of a binary file.- Parameters:
user- optional run-as userpath- 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
Retrieve the device date in the following format:YYYY-mm-dd_HH:MM:SSorYYYY-mm-dd_HH:MM:SS_TZDwhere 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
Execute a shell command and log its output.- Parameters:
user- optional run-as userarguments- shell command arguments- Returns:
- ADB result
-
shell
Execute a shell command.- Parameters:
user- optional run-as userarguments- shell command arguments- Returns:
- ADB result
-
shell
Execute a shell command.- Parameters:
timeout- optional timeout in millisecondsdeviceSerial- optional target device serialuser- optional run-as userarguments- shell command arguments- Returns:
- ADB result
-
shell
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 millisecondsdeviceSerial- optional target device serialuser- optional run-as userarguments- shell command argumentslogOnResult- true to log command output- Returns:
- ADB result
-
executeOn
Execute a command using ADB. Do not provide "-s ..." manually, use the appropriate argument instead.- Parameters:
timeout- null to use a default timeoutdeviceSerial- optional, leave null to let ADB decide on which device the command should be executedarguments- ADB arguments- Returns:
- command output bytes, or null on error
-
execute
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 toProcessExecfor timeout meaningarguments- 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 stdoutarguments- 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 deviceuser- optional userarguments- adb arguments- Returns:
- a process wrapper object; null on error
- Throws:
IOException- on error
-
toString
-