NativeDevice

public class NativeDevice
extends Object implements IManagedTestDevice

java.lang.Object
   ↳ com.android.tradefed.device.NativeDevice
Known Direct Subclasses
TestDevice Implementation of a ITestDevice for a full stack android device  
Known Indirect Subclasses
RemoteAndroidDevice Implementation of a ITestDevice for a full stack android device connected via adb connect. 


Default implementation of a ITestDevice Non-full stack android devices.

Summary

Nested classes

class NativeDevice.AdbAction

A NativeDevice.DeviceAction for running a OS 'adb ....' command. 

interface NativeDevice.DeviceAction

Interface for a generic device communication attempt. 

Constants

String BUILD_CODENAME_PROP

String BUILD_ID_PROP

String BUILD_TAGS

int INVALID_USER_ID

Value returned for any invalid/not found user id: UserHandle defined the -10000 value

String MAC_ADDRESS_COMMAND

String MAC_ADDRESS_PATTERN

long MAX_HOST_DEVICE_TIME_OFFSET

int MAX_RETRY_ATTEMPTS

the default number of command retry attempts to perform

int NONE_RECOVERY_MODE_DELAY

The time in ms to wait for a recovery that we skip because of the NONE mode

Fields

static final Pattern INPUT_DISPATCH_STATE_REGEX

regex to match input dispatch readiness line

protected TestDeviceOptions mOptions

protected final IDeviceStateMonitor mStateMonitor

Public constructors

NativeDevice(IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)

Creates a TestDevice.

Public methods

boolean checkConnectivity()

Check that device has network connectivity.

boolean clearErrorDialogs()

Attempt to dismiss any error dialogs currently displayed on device UI.

void clearLastConnectedWifiNetwork()

Clears the last connected wifi network.

void clearLogcat()

Deletes any accumulated logcat data.

boolean connectToWifiNetwork(String wifiSsid, String wifiPsk)

Connects to a wifi network.

boolean connectToWifiNetwork(String wifiSsid, String wifiPsk, boolean scanSsid)

Connects to a wifi network.

boolean connectToWifiNetworkIfNeeded(String wifiSsid, String wifiPsk, boolean scanSsid)

A variant of connectToWifiNetwork(String, String) that only connects if device currently does not have network connectivity.

boolean connectToWifiNetworkIfNeeded(String wifiSsid, String wifiPsk)

A variant of connectToWifiNetwork(String, String) that only connects if device currently does not have network connectivity.

int createUser(String name, boolean guest, boolean ephemeral)

Create a user with a given name and the provided flags

int createUser(String name)

Create a user with a given name and default flags 0.

boolean disableAdbRoot()

Turns off adb root.

void disableKeyguard()

Attempts to disable the keyguard.

boolean disableNetworkMonitor()

Disables network monitoring on device.

boolean disconnectFromWifi()

Disconnects from a wifi network.

boolean doesFileExist(String destPath)

Helper method to determine if file on device exists.

boolean enableAdbRoot()

Turns on adb root.

boolean enableNetworkMonitor()

Enables network monitoring on device.

boolean encryptDevice(boolean inplace)

Encrypts the device.

String executeAdbCommand(String... cmdArgs)

Helper method which executes a adb command as a system command.

CommandResult executeFastbootCommand(String... cmdArgs)

Helper method which executes a fastboot command as a system command with a default timeout of 2 minutes.

CommandResult executeFastbootCommand(long timeout, String... cmdArgs)

Helper method which executes a fastboot command as a system command.

CommandResult executeLongFastbootCommand(String... cmdArgs)

Helper method which executes a long running fastboot command as a system command.

String executeShellCommand(String command)

Helper method which executes a adb shell command and returns output as a String.

void executeShellCommand(String command, IShellOutputReceiver receiver, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)

Executes a adb shell command, with more parameters to control command behavior.

void executeShellCommand(String command, IShellOutputReceiver receiver)

Executes the given adb shell command, retrying multiple times if command fails.

CommandResult fastbootWipePartition(String partition)

Helper method which wipes a partition for the device.

DeviceAllocationState getAllocationState()

Return the current allocation state of device

String getAndroidId(int userId)

Find and return the android-id associated to a userId, null if not found.

Map<Integer, String> getAndroidIds()

Create a Map of android ids found matching user ids.

int getApiLevel()

Get the device API Level.

PackageInfo getAppPackageInfo(String packageName)

Fetch information about a package installed on device.

String getBasebandVersion()

Convenience method to get baseband (radio) version of this device.

String getBootloaderVersion()

Convenience method to get the bootloader version of this device.

InputStreamSource getBugreport()

Retrieves a bugreport from the device.

InputStreamSource getBugreportz()

Retrieves a bugreportz from the device.

String getBuildAlias()

Retrieve the alias of the build that the device is currently running.

String getBuildFlavor()

Retrieve the build flavor for the device.

String getBuildId()

Retrieve the build the device is currently running.

String getBuildSigningKeys()

Returns the key type used to sign the device image

Typically Android devices may be signed with test-keys (like in AOSP) or release-keys (controlled by individual device manufacturers)

String[] getChildren(String path)

Alternative to using IFileEntry that sometimes won't work because of permissions.

int getCurrentUser()

Return the id of the current running user.

String getDeviceClass()

Get the device class.

long getDeviceDate()

Return the date of the device.

DeviceDescriptor getDeviceDescriptor()

Return a DeviceDescriptor from the device information to get info on it without passing the actual device object.

TestDeviceState getDeviceState()

Get the device's state.

InputStreamSource getEmulatorOutput()

Get the stream of emulator stdout and stderr

Process getEmulatorProcess()

Return the Process corresponding to this emulator.

long getExternalStoreFreeSpace()

Helper method to determine amount of free space on device external storage.

String getFastbootPath()

Returns the path of the fastboot binary being used.

String getFastbootProductType()

Convenience method to get the product type of this device when its in fastboot mode.

String getFastbootProductVariant()

Convenience method to get the product type of this device when its in fastboot mode.

IFileEntry getFileEntry(String path)

Retrieve a reference to a remote file on device.

IDevice getIDevice()

Returns a reference to the associated ddmlib IDevice.

Set<String> getInstalledPackageNames()

Fetch the application package names present on the device.

String getIpAddress()

Gets the device's IP address.

KeyguardControllerState getKeyguardState()

Return an object to get the current state of the keyguard or null if not supported.

InputStreamSource getLogcat()

Grabs a snapshot stream of the logcat data.

InputStreamSource getLogcat(int maxBytes)

Grabs a snapshot stream of the last maxBytes of captured logcat data.

InputStreamSource getLogcatDump()

Get a dump of the current logcat for device.

InputStreamSource getLogcatSince(long date)

Grabs a snapshot stream of captured logcat data starting the date provided.

String getMacAddress()

Returns the MAC address of the device, null if it fails to query from the device.

int getMaxNumberOfUsersSupported()

Get the maximum number of supported users.

IDeviceStateMonitor getMonitor()

Return the IDeviceStateMonitor associated with device.

String getMountPoint(String mountName)

Returns a mount point.

ITestDevice.MountPointInfo getMountPointInfo(String mountpoint)

Returns a ITestDevice.MountPointInfo corresponding to the specified mountpoint path, or null if that path has nothing mounted or otherwise does not appear in /proc/mounts as a mountpoint.

List<ITestDevice.MountPointInfo> getMountPointInfo()

Returns a parsed version of the information in /proc/mounts on the device

TestDeviceOptions getOptions()

Fetch the test options for the device.

Integer getPrimaryUserId()

Returns the primary user id.

ProcessInfo getProcessByName(String processName)

Helper method runs the "ps" command and returns USER, PID and NAME of the given process name.

List<ProcessInfo> getProcesses()

Helper method runs the "ps" command and returns list of USER, PID and NAME of all the processes.

String getProductType()

Convenience method to get the product type of this device.

String getProductVariant()

Convenience method to get the product variant of this device.

String getProperty(String name)

Retrieve the given property value from the device.

ITestDevice.RecoveryMode getRecoveryMode()

Get the current recovery mode used for the device.

InputStreamSource getScreenshot(String format)

Grabs a screenshot from the device.

InputStreamSource getScreenshot(String format, boolean rescale)

Grabs a screenshot from the device.

InputStreamSource getScreenshot()

Grabs a screenshot from the device.

String getSerialNumber()

Convenience method to get serial number of this device.

String getSetting(int userId, String namespace, String key)

Return the value of the requested setting.

String getSetting(String namespace, String key)

See getSetting(int, String, String) and performed on system user.

String getSimOperator()

Return the SIM card operator or null if device is not available.

String getSimState()

Return the SIM card state or null if device is not available.

Set<String> getUninstallablePackageNames()

Fetch the application package names that can be uninstalled.

boolean getUseFastbootErase()

Get whether to use fastboot erase or fastboot format to wipe a partition on the device.

int getUserFlags(int userId)

Find and return the flags of a given user.

int getUserSerialNumber(int userId)

Return the serial number associated to the userId if found, -10000 in any other cases.

IManagedTestDevice.DeviceEventResponse handleAllocationEvent(DeviceEvent event)

Process the given DeviceEvent.

Process the DeviceEvent, which may or may not transition this device to a new allocation state.

boolean hasFeature(String feature)

Check if a feature is available on a device.

String installPackage(File packageFile, boolean reinstall, boolean grantPermissions, String... extraArgs)

Install an Android package on device.

String installPackage(File packageFile, boolean reinstall, String... extraArgs)

Install an Android package on device.

String installPackageForUser(File packageFile, boolean reinstall, int userId, String... extraArgs)

Install an Android package on device for a given user.

String installPackageForUser(File packageFile, boolean reinstall, boolean grantPermissions, int userId, String... extraArgs)

Install an Android package on device for a given user.

boolean isAdbRoot()

boolean isAdbTcp()
boolean isDeviceEncrypted()

Returns if the device is encrypted.

boolean isDirectory(String path)

Return True if the path on the device is a directory, false otherwise.

boolean isEnableAdbRoot()
boolean isEncryptionSupported()

Returns if encryption is supported on the device.

boolean isFastbootEnabled()

Return if fastboot is available for the device.

boolean isHeadless()

Return true if the device is headless (no screen), false otherwise.

boolean isMultiUserSupported()

Determines if multi user is supported.

boolean isRuntimePermissionSupported()

Check whether platform on device supports runtime permission granting

boolean isUserRunning(int userId)

Check if a given user is running.

boolean isWifiEnabled()

Test if wifi is enabled.

ArrayList<Integer> listUsers()

Gets the list of users on the device.

boolean logBugreport(String dataName, ITestLogger listener)

Helper method to take a bugreport and log it to the reporters.

void nonBlockingReboot()

Issues a command to reboot device and returns on command complete and when device is no longer visible to adb.

void postAdbRootAction()

Override if the device needs some specific actions to be taken after adb root and before the device is back online.

void postAdbUnrootAction()

Override if the device needs some specific actions to be taken after adb unroot and before the device is back online.

void postBootSetup()

Perform instructions to configure device for testing that after every boot.

void postInvocationTearDown()

Extra steps for device specific required clean up that will be executed after the invocation is done.

void preInvocationSetup(IBuildInfo info)

Extra steps for device specific required setup that will be executed on the device prior to the invocation flow.

boolean pullDir(String deviceFilePath, File localDir)

Recursively pull directory contents from device.

boolean pullFile(String remoteFilePath, File localFile)

Retrieves a file off device.

File pullFile(String remoteFilePath)

Retrieves a file off device, stores it in a local temporary File, and returns that File.

File pullFileFromExternal(String remoteFilePath)

A convenience method to retrieve a file from the device's external storage, stores it in a local temporary File, and return a reference to that File.

boolean pushDir(File localFileDir, String deviceFilePath)

Recursively push directory contents to device.

boolean pushFile(File localFile, String remoteFilePath)

Push a file to device

boolean pushString(String contents, String remoteFilePath)

Push file created from a string to device

void reboot()

Reboots the device into adb mode.

void rebootIntoBootloader()

Reboots the device into bootloader mode.

void rebootIntoRecovery()

Reboots the device into adb recovery mode.

void rebootUntilOnline()

An alternate to reboot() that only blocks until device is online ie visible to adb.

void recoverDevice()

Attempts to recover device communication.

void remountSystemWritable()

Make the system partition on the device writable.

boolean removeAdmin(String componentName, int userId)

Remove given device admin in given user and return true if it is successful, false otherwise.

void removeOwners()

Remove all existing device profile owners with the best effort.

boolean removeUser(int userId)

Remove a given user from the device.

boolean runInstrumentationTests(IRemoteAndroidTestRunner runner, Collection<ITestRunListener> listeners)

Runs instrumentation tests, and provides device recovery.

boolean runInstrumentationTests(IRemoteAndroidTestRunner runner, ITestRunListener... listeners)

Convenience method for performing runInstrumentationTests(IRemoteAndroidTestRunner, Collection) with one or more listeners passed as parameters.

boolean runInstrumentationTestsAsUser(IRemoteAndroidTestRunner runner, int userId, ITestRunListener... listeners)

Same as runInstrumentationTests(IRemoteAndroidTestRunner, ITestRunListener) but runs the test for a given user.

boolean runInstrumentationTestsAsUser(IRemoteAndroidTestRunner runner, int userId, Collection<ITestRunListener> listeners)

Same as runInstrumentationTests(IRemoteAndroidTestRunner, Collection) but runs the test for the given user.

void setDate(Date date)

Sets the date on device

Note: setting date on device requires root

boolean setDeviceOwner(String componentName, int userId)

Set a device admin component as device owner in given user.

void setDeviceState(TestDeviceState deviceState)

Update the device's state.

void setEmulatorOutputStream(SizeLimitedOutputStream output)

For emulator set SizeLimitedOutputStream to log output

void setEmulatorProcess(Process p)

Sets the Process, when this device is an emulator.

void setFastbootEnabled(boolean fastbootEnabled)

Set the fastboot option for the device.

void setFastbootPath(String fastbootPath)

Sets the path to the fastboot binary that should be used.

void setIDevice(IDevice newDevice)

Update the IDevice associated with this ITestDevice.

void setOptions(TestDeviceOptions options)

Set the TestDeviceOptions for the device

void setRecovery(IDeviceRecovery recovery)

Set the IDeviceRecovery to use for this device.

void setRecoveryMode(ITestDevice.RecoveryMode mode)

Set the current recovery mode to use for the device.

void setSetting(String namespace, String key, String value)

See setSetting(int, String, String, String) and performed on system user.

void setSetting(int userId, String namespace, String key, String value)

Add a setting value to the namespace of a given user.

void setUseFastbootErase(boolean useFastbootErase)

Set whether to use fastboot erase or fastboot format to wipe a partition on the device.

void startLogcat()

Start capturing logcat output from device in the background.

boolean startUser(int userId)

Starts a given user in the background if it is currently stopped.

void stopEmulatorOutput()

Close and delete the emulator output.

void stopLogcat()

Stop capturing logcat output from device, and discard currently saved logcat data.

boolean stopUser(int userId)

Stops a given user.

boolean stopUser(int userId, boolean waitFlag, boolean forceFlag)

Stop a given user.

String switchToAdbTcp()

Switch device to adb-over-tcp mode.

boolean switchToAdbUsb()

Switch device to adb over usb mode.

boolean switchUser(int userId)

Switch to another userId with a default timeout.

boolean switchUser(int userId, long timeout)

Switch to another userId with the provided timeout as deadline.

boolean syncFiles(File localFileDir, String deviceFilePath)

Incrementally syncs the contents of a local file directory to device.

Bugreport takeBugreport()

Take a bugreport and returns it inside a Bugreport object to handle it.

boolean unencryptDevice()

Unencrypts the device.

String uninstallPackage(String packageName)

Uninstall an Android package from device.

boolean unlockDevice()

Unlocks the device if the device is in an encrypted state.

boolean waitForBootComplete(long timeOut)

Blocks until the device's boot complete flag is set.

void waitForDeviceAvailable()

Waits for the device to be responsive and available for testing.

void waitForDeviceAvailable(long waitTime)

Waits for the device to be responsive and available for testing.

boolean waitForDeviceInRecovery(long waitTime)

Blocks for the device to be in the 'adb recovery' state (note this is distinct from IDeviceRecovery).

boolean waitForDeviceNotAvailable(long waitTime)

Blocks for the device to be not available ie missing from adb

void waitForDeviceOnline()

Blocks until device is visible via adb.

void waitForDeviceOnline(long waitTime)

Blocks until device is visible via adb.

boolean waitForDeviceShell(long waitTime)

Waits for device to be responsive to a basic adb shell command.

Protected methods

void checkApiLevelAgainst(String feature, int strictMinLevel)
void doAdbReboot(String into)

Perform a adb reboot.

void ensureRuntimePermissionSupported()

helper method to throw exception if runtime permission isn't supported

File getBugreportzInternal()

Internal Helper method to get the bugreportz zip file as a File.

long getDeviceTimeOffset(Date date)

Helper to get the time difference between the device and the host.

IRunUtil getRunUtil()

Get the RunUtil instance to use.

boolean isNewer(File localFile, IFileEntry entry)

Return true if local file is newer than remote file.

boolean performDeviceAction(String actionDescription, NativeDevice.DeviceAction action, int retryAttempts)

Performs an action on this device.

void prePostBootSetup()

Allows each device type (AndroidNativeDevice, TestDevice) to override this method for specific post boot setup.

void setLogStartDelay(int delay)

Sets the time in ms to wait before starting logcat capture for a online device.

void waitForDeviceNotAvailable(String operationDesc, long time)

Constants

BUILD_CODENAME_PROP

String BUILD_CODENAME_PROP

Constant Value: "ro.build.version.codename"

BUILD_ID_PROP

String BUILD_ID_PROP

Constant Value: "ro.build.version.incremental"

BUILD_TAGS

String BUILD_TAGS

Constant Value: "ro.build.tags"

INVALID_USER_ID

int INVALID_USER_ID

Value returned for any invalid/not found user id: UserHandle defined the -10000 value

Constant Value: -10000 (0xffffd8f0)

MAC_ADDRESS_COMMAND

String MAC_ADDRESS_COMMAND

Constant Value: "cat /sys/class/net/wlan0/address"

MAC_ADDRESS_PATTERN

String MAC_ADDRESS_PATTERN

Constant Value: "([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}"

MAX_HOST_DEVICE_TIME_OFFSET

long MAX_HOST_DEVICE_TIME_OFFSET

Constant Value: 5000 (0x0000000000001388)

MAX_RETRY_ATTEMPTS

int MAX_RETRY_ATTEMPTS

the default number of command retry attempts to perform

Constant Value: 2 (0x00000002)

NONE_RECOVERY_MODE_DELAY

int NONE_RECOVERY_MODE_DELAY

The time in ms to wait for a recovery that we skip because of the NONE mode

Constant Value: 1000 (0x000003e8)

Fields

INPUT_DISPATCH_STATE_REGEX

Pattern INPUT_DISPATCH_STATE_REGEX

regex to match input dispatch readiness line

mOptions

TestDeviceOptions mOptions

mStateMonitor

IDeviceStateMonitor mStateMonitor

Public constructors

NativeDevice

NativeDevice (IDevice device, 
                IDeviceStateMonitor stateMonitor, 
                IDeviceMonitor allocationMonitor)

Creates a TestDevice.

Parameters
device IDevice: the associated IDevice

stateMonitor IDeviceStateMonitor: the IDeviceStateMonitor mechanism to use

allocationMonitor IDeviceMonitor: the IDeviceMonitor to inform of allocation state changes. Can be null

Public methods

checkConnectivity

boolean checkConnectivity ()

Check that device has network connectivity.

Returns
boolean true if device has a working network connection, false overwise.

Throws
DeviceNotAvailableException

clearErrorDialogs

boolean clearErrorDialogs ()

Attempt to dismiss any error dialogs currently displayed on device UI.

Returns
boolean true if no dialogs were present or dialogs were successfully cleared. false otherwise.

Throws
DeviceNotAvailableException

clearLastConnectedWifiNetwork

void clearLastConnectedWifiNetwork ()

Clears the last connected wifi network. This should be called when starting a new invocation to avoid connecting to the wifi network used in the previous test after device reboots.

clearLogcat

void clearLogcat ()

Deletes any accumulated logcat data.

This is useful for cases when you want to ensure getLogcat() only returns log data produced after a certain point (such as after flashing a new device build, etc).

connectToWifiNetwork

boolean connectToWifiNetwork (String wifiSsid, 
                String wifiPsk)

Connects to a wifi network.

Turns on wifi and blocks until a successful connection is made to the specified wifi network. Once a connection is made, the instance will try to restore the connection after every reboot until disconnectFromWifi() or clearLastConnectedWifiNetwork() is called.

Parameters
wifiSsid String: the wifi ssid to connect to

wifiPsk String: PSK passphrase or null if unencrypted

Returns
boolean true if connected to wifi network successfully. false otherwise

Throws
DeviceNotAvailableException

connectToWifiNetwork

boolean connectToWifiNetwork (String wifiSsid, 
                String wifiPsk, 
                boolean scanSsid)

Connects to a wifi network.

Turns on wifi and blocks until a successful connection is made to the specified wifi network. Once a connection is made, the instance will try to restore the connection after every reboot until disconnectFromWifi() or clearLastConnectedWifiNetwork() is called.

Parameters
wifiSsid String: the wifi ssid to connect to

wifiPsk String: PSK passphrase or null if unencrypted

scanSsid boolean: whether to scan for hidden SSID for this network.

Returns
boolean true if connected to wifi network successfully. false otherwise

Throws
DeviceNotAvailableException

connectToWifiNetworkIfNeeded

boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk, 
                boolean scanSsid)

A variant of connectToWifiNetwork(String, String) that only connects if device currently does not have network connectivity.

Parameters
scanSsid boolean: whether to scan for hidden SSID for this network

Returns
boolean true if connected to wifi network successfully. false otherwise

Throws
DeviceNotAvailableException

connectToWifiNetworkIfNeeded

boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk)

A variant of connectToWifiNetwork(String, String) that only connects if device currently does not have network connectivity.

Returns
boolean true if connected to wifi network successfully. false otherwise

Throws
DeviceNotAvailableException

createUser

int createUser (String name, 
                boolean guest, 
                boolean ephemeral)

Create a user with a given name and the provided flags

Parameters
name String: of the user to create on the device

guest boolean: enable the user flag --guest during creation

ephemeral boolean: enable the user flag --ephemeral during creation

Returns
int id of the created user

Throws
DeviceNotAvailableException
IllegalStateException

createUser

int createUser (String name)

Create a user with a given name and default flags 0.

Parameters
name String: of the user to create on the device

Returns
int the integer for the user id created

Throws
DeviceNotAvailableException
IllegalStateException

disableAdbRoot

boolean disableAdbRoot ()

Turns off adb root.

Disabling adb root may cause device to disconnect from adb. This method will block until device is available.

Returns
boolean true if successful.

Throws
DeviceNotAvailableException

disableKeyguard

void disableKeyguard ()

Attempts to disable the keyguard.

First wait for the input dispatch to become ready, this happens around the same time when the device reports BOOT_COMPLETE, apparently asynchronously, because current framework implementation has occasional race condition. Then command is sent to dismiss keyguard (works on non-secure ones only)

Throws
DeviceNotAvailableException

disableNetworkMonitor

boolean disableNetworkMonitor ()

Disables network monitoring on device.

Returns
boolean true if monitoring is disabled successfully. false if it failed.

Throws
DeviceNotAvailableException

disconnectFromWifi

boolean disconnectFromWifi ()

Disconnects from a wifi network.

Removes all networks from known networks list and disables wifi.

Returns
boolean true if disconnected from wifi network successfully. false if disconnect failed.

Throws
DeviceNotAvailableException

doesFileExist

boolean doesFileExist (String destPath)

Helper method to determine if file on device exists.

Parameters
destPath String: the absolute path of file on device to check

Returns
boolean true if file exists, false otherwise.

Throws
DeviceNotAvailableException

enableAdbRoot

boolean enableAdbRoot ()

Turns on adb root. If the "enable-root" setting is "false", will log a message and return without enabling root.

Enabling adb root may cause device to disconnect from adb. This method will block until device is available.

Returns
boolean true if successful.

Throws
DeviceNotAvailableException

enableNetworkMonitor

boolean enableNetworkMonitor ()

Enables network monitoring on device.

Returns
boolean true if monitoring is enabled successfully. false if it failed.

Throws
DeviceNotAvailableException

encryptDevice

boolean encryptDevice (boolean inplace)

Encrypts the device.

Encrypting the device may be done inplace or with a wipe. Inplace encryption will not wipe any data on the device but normally takes a couple orders of magnitude longer than the wipe.

This method will reboot the device if it is not already encrypted and will block until device is online. Also, it will not decrypt the device after the reboot. Therefore, the device might not be fully booted and/or ready to be tested when this method returns.

Parameters
inplace boolean: if the encryption process should take inplace and the device should not be wiped.

Returns
boolean true if successful.

Throws
DeviceNotAvailableException
UnsupportedOperationException

executeAdbCommand

String executeAdbCommand (String... cmdArgs)

Helper method which executes a adb command as a system command.

executeShellCommand(String) should be used instead wherever possible, as that method provides better failure detection and performance.

Parameters
cmdArgs String: the adb command and arguments to run

Returns
String the stdout from command. null if command failed to execute.

Throws
DeviceNotAvailableException

executeFastbootCommand

CommandResult executeFastbootCommand (String... cmdArgs)

Helper method which executes a fastboot command as a system command with a default timeout of 2 minutes.

Expected to be used when device is already in fastboot mode.

Parameters
cmdArgs String: the fastboot command and arguments to run

Returns
CommandResult the CommandResult containing output of command

Throws
DeviceNotAvailableException
UnsupportedOperationException

executeFastbootCommand

CommandResult executeFastbootCommand (long timeout, 
                String... cmdArgs)

Helper method which executes a fastboot command as a system command.

Expected to be used when device is already in fastboot mode.

Parameters
timeout long: the time in milliseconds before the command expire

cmdArgs String: the fastboot command and arguments to run

Returns
CommandResult the CommandResult containing output of command

Throws
DeviceNotAvailableException
UnsupportedOperationException

executeLongFastbootCommand

CommandResult executeLongFastbootCommand (String... cmdArgs)

Helper method which executes a long running fastboot command as a system command.

Identical to executeFastbootCommand(String) except uses a longer timeout.

Parameters
cmdArgs String: the fastboot command and arguments to run

Returns
CommandResult the CommandResult containing output of command

Throws
DeviceNotAvailableException
UnsupportedOperationException

executeShellCommand

String executeShellCommand (String command)

Helper method which executes a adb shell command and returns output as a String.

Parameters
command String: the adb shell command to run

Returns
String the shell output

Throws
DeviceNotAvailableException

executeShellCommand

void executeShellCommand (String command, 
                IShellOutputReceiver receiver, 
                long maxTimeToOutputShellResponse, 
                TimeUnit timeUnit, 
                int retryAttempts)

Executes a adb shell command, with more parameters to control command behavior.

Parameters
command String: the adb shell command to run

receiver IShellOutputReceiver: the IShellOutputReceiver to direct shell output to.

maxTimeToOutputShellResponse long: the maximum amount of time during which the command is allowed to not output any response; unit as specified in timeUnit

timeUnit TimeUnit: unit for maxTimeToOutputShellResponse

retryAttempts int: the maximum number of times to retry command if it fails due to a exception. DeviceNotResponsiveException will be thrown if retryAttempts are performed without success.

Throws
DeviceNotAvailableException

executeShellCommand

void executeShellCommand (String command, 
                IShellOutputReceiver receiver)

Executes the given adb shell command, retrying multiple times if command fails.

A simpler form of executeShellCommand(String, IShellOutputReceiver, long, TimeUnit, int) with default values.

Parameters
command String: the adb shell command to run

receiver IShellOutputReceiver: the IShellOutputReceiver to direct shell output to.

Throws
DeviceNotAvailableException

fastbootWipePartition

CommandResult fastbootWipePartition (String partition)

Helper method which wipes a partition for the device.

If getUseFastbootErase() is true, then fastboot erase will be used to wipe the partition. The device must then create a filesystem the next time the device boots. Otherwise, fastboot format is used which will create a new filesystem on the device.

Expected to be used when device is already in fastboot mode.

Parameters
partition String: the partition to wipe

Returns
CommandResult the CommandResult containing output of command

Throws
DeviceNotAvailableException

getAllocationState

DeviceAllocationState getAllocationState ()

Return the current allocation state of device

Returns
DeviceAllocationState

getAndroidId

String getAndroidId (int userId)

Find and return the android-id associated to a userId, null if not found.

Parameters
userId int

Returns
String

Throws
DeviceNotAvailableException

getAndroidIds

Map<Integer, String> getAndroidIds ()

Create a Map of android ids found matching user ids. There is no insurance that each user id will found an android id associated in this function so some user ids may match null.

Returns
Map<Integer, String> Map of android ids found matching user ids.

Throws
DeviceNotAvailableException

getApiLevel

int getApiLevel ()

Get the device API Level. Defaults to UNKNOWN_API_LEVEL.

Returns
int an integer indicating the API Level of device

Throws
DeviceNotAvailableException

getAppPackageInfo

PackageInfo getAppPackageInfo (String packageName)

Fetch information about a package installed on device.

Parameters
packageName String

Returns
PackageInfo the PackageInfo or null if information could not be retrieved

Throws
DeviceNotAvailableException

getBasebandVersion

String getBasebandVersion ()

Convenience method to get baseband (radio) version of this device. Getting the radio version is device specific, so it might not return the correct information for all devices. This method relies on the gsm.version.baseband propery to return the correct version information. This is not accurate for some CDMA devices and the version returned here might not match the version reported from fastboot and might not return the version for the CDMA radio. TL;DR this method only reports accurate version if the gsm.version.baseband property is the same as the version returned by fastboot getvar version-baseband.

Returns
String the String baseband version or null if it cannot be determined (device has no radio or version string cannot be read)

Throws
DeviceNotAvailableException

getBootloaderVersion

String getBootloaderVersion ()

Convenience method to get the bootloader version of this device.

Will attempt to retrieve bootloader version from the device's current state. (ie if device is in fastboot mode, it will attempt to retrieve version from fastboot)

Returns
String the String bootloader version or null if it cannot be found

Throws
UnsupportedOperationException
DeviceNotAvailableException

getBugreport

InputStreamSource getBugreport ()

Retrieves a bugreport from the device.

The implementation of this is guaranteed to continue to work on a device without an sdcard (or where the sdcard is not yet mounted).

Returns
InputStreamSource An InputStreamSource which will produce the bugreport contents on demand. In case of failure, the InputStreamSource will produce an empty InputStream.

getBugreportz

InputStreamSource getBugreportz ()

Retrieves a bugreportz from the device. Zip format bugreport contains the main bugreport and other log files that are useful for debugging.

Only supported for 'adb version' > 1.0.36

Returns
InputStreamSource a InputStreamSource of the zip file containing the bugreportz, return null in case of failure.

getBuildAlias

String getBuildAlias ()

Retrieve the alias of the build that the device is currently running.

Build alias is usually a more readable string than build id (typically a number for Nexus builds). For example, final Android 4.2 release has build alias JDQ39, and build id 573038

Returns
String the build alias or fall back to build id if it could not be retrieved

Throws
DeviceNotAvailableException

getBuildFlavor

String getBuildFlavor ()

Retrieve the build flavor for the device.

Returns
String the build flavor or null if it could not be retrieved

Throws
DeviceNotAvailableException

getBuildId

String getBuildId ()

Retrieve the build the device is currently running.

Returns
String the build id or UNKNOWN_BUILD_ID if it could not be retrieved

Throws
DeviceNotAvailableException

getBuildSigningKeys

String getBuildSigningKeys ()

Returns the key type used to sign the device image

Typically Android devices may be signed with test-keys (like in AOSP) or release-keys (controlled by individual device manufacturers)

Returns
String The signing key if found, null otherwise.

Throws
DeviceNotAvailableException

getChildren

String[] getChildren (String path)

Alternative to using IFileEntry that sometimes won't work because of permissions.

Parameters
path String: is the path on the device where to do the search

Returns
String[] Array of string containing all the file in a path on the device.

Throws
DeviceNotAvailableException

getCurrentUser

int getCurrentUser ()

Return the id of the current running user.

Returns
int

Throws
DeviceNotAvailableException

getDeviceClass

String getDeviceClass ()

Get the device class.

Returns
String the String device class.

getDeviceDate

long getDeviceDate ()

Return the date of the device.

Returns
long the date of the device in epoch format.

Throws
DeviceNotAvailableException

getDeviceDescriptor

DeviceDescriptor getDeviceDescriptor ()

Return a DeviceDescriptor from the device information to get info on it without passing the actual device object.

Returns
DeviceDescriptor

getDeviceState

TestDeviceState getDeviceState ()

Get the device's state.

Returns
TestDeviceState

getEmulatorOutput

InputStreamSource getEmulatorOutput ()

Get the stream of emulator stdout and stderr

Returns
InputStreamSource emulator output

getEmulatorProcess

Process getEmulatorProcess ()

Return the Process corresponding to this emulator.

Returns
Process the Process or null

getExternalStoreFreeSpace

long getExternalStoreFreeSpace ()

Helper method to determine amount of free space on device external storage.

Returns
long the amount of free space in KB

Throws
DeviceNotAvailableException

getFastbootPath

String getFastbootPath ()

Returns the path of the fastboot binary being used. Still requires isFastbootEnabled() to be true, to have fastboot functions enabled.

Returns
String

getFastbootProductType

String getFastbootProductType ()

Convenience method to get the product type of this device when its in fastboot mode.

This method should only be used if device should be in fastboot. Its a bit safer variant than the generic getProductType() method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.

Returns
String the String product type name or null if it cannot be determined

Throws
DeviceNotAvailableException
UnsupportedOperationException

getFastbootProductVariant

String getFastbootProductVariant ()

Convenience method to get the product type of this device when its in fastboot mode.

This method should only be used if device should be in fastboot. Its a bit safer variant than the generic getProductType() method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.

Returns
String the String product type name or null if it cannot be determined

Throws
DeviceNotAvailableException
UnsupportedOperationException

getFileEntry

IFileEntry getFileEntry (String path)

Retrieve a reference to a remote file on device.

Parameters
path String: the file path to retrieve. Can be an absolute path or path relative to '/'. (ie both "/system" and "system" syntax is supported)

Returns
IFileEntry the IFileEntry or null if file at given path cannot be found

Throws
DeviceNotAvailableException

getIDevice

IDevice getIDevice ()

Returns a reference to the associated ddmlib IDevice.

A new IDevice may be allocated by DDMS each time the device disconnects and reconnects from adb. Thus callers should not keep a reference to the IDevice, because that reference may become stale.

Returns
IDevice the IDevice

getInstalledPackageNames

Set<String> getInstalledPackageNames ()

Fetch the application package names present on the device.

Returns
Set<String> Set of String package names currently installed on the device.

Throws
DeviceNotAvailableException

getIpAddress

String getIpAddress ()

Gets the device's IP address.

Returns
String the device's IP address, or null if device has no IP address

Throws
DeviceNotAvailableException

getKeyguardState

KeyguardControllerState getKeyguardState ()

Return an object to get the current state of the keyguard or null if not supported.

Returns
KeyguardControllerState a KeyguardControllerState containing a snapshot of the state of the keyguard and returns Null if the Keyguard query is not supported.

Throws
DeviceNotAvailableException

getLogcat

InputStreamSource getLogcat ()

Grabs a snapshot stream of the logcat data.

Works in two modes:

  • If the logcat is currently being captured in the background, will return up to getMaxLogcatDataSize() bytes of the current contents of the background logcat capture
  • Otherwise, will return a static dump of the logcat data if device is currently responding

    Returns
    InputStreamSource

  • getLogcat

    InputStreamSource getLogcat (int maxBytes)

    Grabs a snapshot stream of the last maxBytes of captured logcat data.

    Useful for cases when you want to capture frequent snapshots of the captured logcat data without incurring the potentially big disk space penalty of getting the entire getLogcat() snapshot.

    Parameters
    maxBytes int: the maximum amount of data to return. Should be an amount that can comfortably fit in memory

    Returns
    InputStreamSource

    getLogcatDump

    InputStreamSource getLogcatDump ()

    Get a dump of the current logcat for device. Unlike getLogcat(), this method will always return a static dump of the logcat.

    Has the disadvantage that nothing will be returned if device is not reachable.

    Returns
    InputStreamSource a InputStreamSource of the logcat data. An empty stream is returned if fail to capture logcat data.

    getLogcatSince

    InputStreamSource getLogcatSince (long date)

    Grabs a snapshot stream of captured logcat data starting the date provided. The time on the device should be used getDeviceDate().

    Parameters
    date long: in epoch format of when to start the snapshot until present. (can be be obtained using 'date +%s')

    Returns
    InputStreamSource

    getMacAddress

    String getMacAddress ()

    Returns the MAC address of the device, null if it fails to query from the device.

    Returns
    String

    getMaxNumberOfUsersSupported

    int getMaxNumberOfUsersSupported ()

    Get the maximum number of supported users. Defaults to 0.

    Returns
    int an integer indicating the number of supported users

    Throws
    DeviceNotAvailableException

    getMonitor

    IDeviceStateMonitor getMonitor ()

    Return the IDeviceStateMonitor associated with device.

    Returns
    IDeviceStateMonitor

    getMountPoint

    String getMountPoint (String mountName)

    Returns a mount point.

    Queries the device directly if the cached info in IDevice is not available.

    TODO: move this behavior to getMountPoint(String)

    Parameters
    mountName String: the name of the mount point

    Returns
    String the mount point or null

    getMountPointInfo

    ITestDevice.MountPointInfo getMountPointInfo (String mountpoint)

    Returns a ITestDevice.MountPointInfo corresponding to the specified mountpoint path, or null if that path has nothing mounted or otherwise does not appear in /proc/mounts as a mountpoint.

    Parameters
    mountpoint String

    Returns
    ITestDevice.MountPointInfo A List of ITestDevice.MountPointInfo containing the information in "/proc/mounts"

    Throws
    DeviceNotAvailableException

    getMountPointInfo

    List<ITestDevice.MountPointInfo> getMountPointInfo ()

    Returns a parsed version of the information in /proc/mounts on the device

    Returns
    List<ITestDevice.MountPointInfo> A List of ITestDevice.MountPointInfo containing the information in "/proc/mounts"

    Throws
    DeviceNotAvailableException

    getOptions

    TestDeviceOptions getOptions ()

    Fetch the test options for the device.

    Returns
    TestDeviceOptions TestDeviceOptions related to the device under test.

    getPrimaryUserId

    Integer getPrimaryUserId ()

    Returns the primary user id.

    Returns
    Integer the userId of the primary user if there is one, and null if there is no primary user.

    Throws
    DeviceNotAvailableException

    getProcessByName

    ProcessInfo getProcessByName (String processName)

    Helper method runs the "ps" command and returns USER, PID and NAME of the given process name.

    Parameters
    processName String

    Returns
    ProcessInfo ProcessInfo of given processName

    Throws
    DeviceNotAvailableException

    getProcesses

    List<ProcessInfo> getProcesses ()

    Helper method runs the "ps" command and returns list of USER, PID and NAME of all the processes.

    Returns
    List<ProcessInfo> List of ProcessInfo objects

    Throws
    DeviceNotAvailableException

    getProductType

    String getProductType ()

    Convenience method to get the product type of this device.

    This method will work if device is in either adb or fastboot mode.

    Returns
    String the String product type name. Will not be null

    Throws
    DeviceNotAvailableException

    getProductVariant

    String getProductVariant ()

    Convenience method to get the product variant of this device.

    This method will work if device is in either adb or fastboot mode.

    Returns
    String the String product variant name or null if it cannot be determined

    Throws
    DeviceNotAvailableException

    getProperty

    String getProperty (String name)

    Retrieve the given property value from the device.

    Parameters
    name String: the property name

    Returns
    String the property value or null if it does not exist

    Throws
    DeviceNotAvailableException

    getRecoveryMode

    ITestDevice.RecoveryMode getRecoveryMode ()

    Get the current recovery mode used for the device.

    Returns
    ITestDevice.RecoveryMode the current recovery mode used for the device.

    getScreenshot

    InputStreamSource getScreenshot (String format)

    Grabs a screenshot from the device. Recommended to use getScreenshot(format) instead with JPEG encoding for smaller size

    Parameters
    format String: supported PNG, JPEG

    Returns
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    Throws
    DeviceNotAvailableException

    getScreenshot

    InputStreamSource getScreenshot (String format, 
                    boolean rescale)

    Grabs a screenshot from the device. Recommended to use getScreenshot(String) instead with JPEG encoding for smaller size.

    Parameters
    format String: supported PNG, JPEG

    rescale boolean: if screenshot should be rescaled to reduce the size of resulting image

    Returns
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    Throws
    DeviceNotAvailableException

    getScreenshot

    InputStreamSource getScreenshot ()

    Grabs a screenshot from the device.

    Returns
    InputStreamSource a InputStreamSource of the screenshot in png format, or null if the screenshot was not successful.

    Throws
    DeviceNotAvailableException

    getSerialNumber

    String getSerialNumber ()

    Convenience method to get serial number of this device.

    Returns
    String the String serial number

    getSetting

    String getSetting (int userId, 
                    String namespace, 
                    String key)

    Return the value of the requested setting. namespace must be one of: {"system", "secure", "global"}

    Parameters
    userId int

    namespace String

    key String

    Returns
    String the value associated with the namespace:key of a user. Null if not found.

    Throws
    DeviceNotAvailableException

    getSetting

    String getSetting (String namespace, 
                    String key)

    See getSetting(int, String, String) and performed on system user.

    Parameters
    namespace String

    key String

    Returns
    String

    Throws
    DeviceNotAvailableException

    getSimOperator

    String getSimOperator ()

    Return the SIM card operator or null if device is not available.

    Returns
    String

    getSimState

    String getSimState ()

    Return the SIM card state or null if device is not available.

    Returns
    String

    getUninstallablePackageNames

    Set<String> getUninstallablePackageNames ()

    Fetch the application package names that can be uninstalled. This is presently defined as non-system packages, and updated system packages.

    Returns
    Set<String> Set of uninstallable String package names currently installed on the device.

    Throws
    DeviceNotAvailableException

    getUseFastbootErase

    boolean getUseFastbootErase ()

    Get whether to use fastboot erase or fastboot format to wipe a partition on the device.

    Returns
    boolean true if fastboot erase will be used or false if fastboot format will be used.

    getUserFlags

    int getUserFlags (int userId)

    Find and return the flags of a given user. Flags are defined in "android.content.pm.UserInfo" class in Android Open Source Project.

    Parameters
    userId int

    Returns
    int the flags associated with the userId provided if found, -10000 in any other cases.

    Throws
    DeviceNotAvailableException

    getUserSerialNumber

    int getUserSerialNumber (int userId)

    Return the serial number associated to the userId if found, -10000 in any other cases.

    Parameters
    userId int

    Returns
    int

    Throws
    DeviceNotAvailableException

    handleAllocationEvent

    IManagedTestDevice.DeviceEventResponse handleAllocationEvent (DeviceEvent event)

    Process the given DeviceEvent. May transition device to new state. Will inform the IDeviceMonitor of any state transitions.

    Process the DeviceEvent, which may or may not transition this device to a new allocation state.

    Parameters
    event DeviceEvent

    Returns
    IManagedTestDevice.DeviceEventResponse

    hasFeature

    boolean hasFeature (String feature)

    Check if a feature is available on a device.

    Parameters
    feature String: which format should be "feature:".

    Returns
    boolean True if feature is found, false otherwise.

    Throws
    DeviceNotAvailableException

    installPackage

    String installPackage (File packageFile, 
                    boolean reinstall, 
                    boolean grantPermissions, 
                    String... extraArgs)

    Install an Android package on device.

    Note: Only use cases that requires explicit control of granting runtime permission at install time should call this function.

    Parameters
    packageFile File: the apk file to install

    reinstall boolean: true if a reinstall should be performed

    grantPermissions boolean: if all runtime permissions should be granted at install time

    extraArgs String: optional extra arguments to pass. See 'adb shell pm install --help' for available options.

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    installPackage

    String installPackage (File packageFile, 
                    boolean reinstall, 
                    String... extraArgs)

    Install an Android package on device.

    Parameters
    packageFile File: the apk file to install

    reinstall boolean: true if a reinstall should be performed

    extraArgs String: optional extra arguments to pass. See 'adb shell pm install --help' for available options.

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    installPackageForUser

    String installPackageForUser (File packageFile, 
                    boolean reinstall, 
                    int userId, 
                    String... extraArgs)

    Install an Android package on device for a given user.

    Parameters
    packageFile File: the apk file to install

    reinstall boolean: true if a reinstall should be performed

    userId int: the integer user id to install for.

    extraArgs String: optional extra arguments to pass. See 'adb shell pm install --help' for available options.

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    installPackageForUser

    String installPackageForUser (File packageFile, 
                    boolean reinstall, 
                    boolean grantPermissions, 
                    int userId, 
                    String... extraArgs)

    Install an Android package on device for a given user.

    Note: Only use cases that requires explicit control of granting runtime permission at install time should call this function.

    Parameters
    packageFile File: the apk file to install

    reinstall boolean: true if a reinstall should be performed

    grantPermissions boolean: if all runtime permissions should be granted at install time

    userId int: the integer user id to install for.

    extraArgs String: optional extra arguments to pass. See 'adb shell pm install --help' for available options.

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    isAdbRoot

    boolean isAdbRoot ()

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isAdbTcp

    boolean isAdbTcp ()

    Returns
    boolean

    isDeviceEncrypted

    boolean isDeviceEncrypted ()

    Returns if the device is encrypted.

    Returns
    boolean true if the device is encrypted.

    Throws
    DeviceNotAvailableException

    isDirectory

    boolean isDirectory (String path)

    Return True if the path on the device is a directory, false otherwise.

    Parameters
    path String

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isEnableAdbRoot

    boolean isEnableAdbRoot ()

    Returns
    boolean true if adb root should be enabled on device

    isEncryptionSupported

    boolean isEncryptionSupported ()

    Returns if encryption is supported on the device.

    Returns
    boolean true if the device supports encryption.

    Throws
    DeviceNotAvailableException

    isFastbootEnabled

    boolean isFastbootEnabled ()

    Return if fastboot is available for the device.

    Returns
    boolean

    isHeadless

    boolean isHeadless ()

    Return true if the device is headless (no screen), false otherwise.

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isMultiUserSupported

    boolean isMultiUserSupported ()

    Determines if multi user is supported.

    Returns
    boolean true if multi user is supported, false otherwise

    Throws
    DeviceNotAvailableException

    isRuntimePermissionSupported

    boolean isRuntimePermissionSupported ()

    Check whether platform on device supports runtime permission granting

    Returns
    boolean True if runtime permission are supported, false otherwise.

    Throws
    DeviceNotAvailableException

    isUserRunning

    boolean isUserRunning (int userId)

    Check if a given user is running.

    Parameters
    userId int

    Returns
    boolean True if the user is running, false in every other cases.

    Throws
    DeviceNotAvailableException

    isWifiEnabled

    boolean isWifiEnabled ()

    Test if wifi is enabled.

    Checks if wifi is enabled on device. Useful for asserting wifi status before tests that shouldn't run with wifi, e.g. mobile data tests.

    Returns
    boolean true if wifi is enabled. false if disabled

    Throws
    DeviceNotAvailableException

    listUsers

    ArrayList<Integer> listUsers ()

    Gets the list of users on the device. Defaults to null.

    Returns
    ArrayList<Integer> the list of user ids or null if there was an error.

    Throws
    DeviceNotAvailableException

    logBugreport

    boolean logBugreport (String dataName, 
                    ITestLogger listener)

    Helper method to take a bugreport and log it to the reporters.

    Parameters
    dataName String: name under which the bugreport will be reported.

    listener ITestLogger: an ITestLogger to log the bugreport.

    Returns
    boolean True if the logging was sucessful, false otherwise.

    nonBlockingReboot

    void nonBlockingReboot ()

    Issues a command to reboot device and returns on command complete and when device is no longer visible to adb.

    Throws
    DeviceNotAvailableException

    postAdbRootAction

    void postAdbRootAction ()

    Override if the device needs some specific actions to be taken after adb root and before the device is back online. Default implementation doesn't include any addition actions. adb root is not guaranteed to be enabled at this stage.

    Throws
    DeviceNotAvailableException

    postAdbUnrootAction

    void postAdbUnrootAction ()

    Override if the device needs some specific actions to be taken after adb unroot and before the device is back online. Default implementation doesn't include any additional actions. adb root is not guaranteed to be disabled at this stage.

    Throws
    DeviceNotAvailableException

    postBootSetup

    void postBootSetup ()

    Perform instructions to configure device for testing that after every boot.

    Should be called after device is fully booted/available

    In normal circumstances this method doesn't need to be called explicitly, as implementations should perform these steps automatically when performing a reboot.

    Where it may need to be called is when device reboots due to other events (eg when a fastboot update command has completed)

    Throws
    DeviceNotAvailableException

    postInvocationTearDown

    void postInvocationTearDown ()

    Extra steps for device specific required clean up that will be executed after the invocation is done.

    preInvocationSetup

    void preInvocationSetup (IBuildInfo info)

    Extra steps for device specific required setup that will be executed on the device prior to the invocation flow.

    Parameters
    info IBuildInfo

    Throws
    TargetSetupError
    DeviceNotAvailableException

    pullDir

    boolean pullDir (String deviceFilePath, 
                    File localDir)

    Recursively pull directory contents from device.

    Parameters
    deviceFilePath String: the absolute file path of the remote source

    localDir File: the local directory to pull files into

    Returns
    boolean true if file was pulled successfully. false otherwise.

    Throws
    DeviceNotAvailableException

    pullFile

    boolean pullFile (String remoteFilePath, 
                    File localFile)

    Retrieves a file off device.

    Parameters
    remoteFilePath String: the absolute path to file on device.

    localFile File: the local file to store contents in. If non-empty, contents will be replaced.

    Returns
    boolean true if file was retrieved successfully. false otherwise.

    Throws
    DeviceNotAvailableException

    pullFile

    File pullFile (String remoteFilePath)

    Retrieves a file off device, stores it in a local temporary File, and returns that File.

    Parameters
    remoteFilePath String: the absolute path to file on device.

    Returns
    File A File containing the contents of the device file, or null if the copy failed for any reason (including problems with the host filesystem)

    Throws
    DeviceNotAvailableException

    pullFileFromExternal

    File pullFileFromExternal (String remoteFilePath)

    A convenience method to retrieve a file from the device's external storage, stores it in a local temporary File, and return a reference to that File.

    Parameters
    remoteFilePath String: the path to file on device, relative to the device's external storage mountpoint

    Returns
    File A File containing the contents of the device file, or null if the copy failed for any reason (including problems with the host filesystem)

    Throws
    DeviceNotAvailableException

    pushDir

    boolean pushDir (File localFileDir, 
                    String deviceFilePath)

    Recursively push directory contents to device.

    Parameters
    localFileDir File: the local directory to push

    deviceFilePath String: the absolute file path of the remote destination

    Returns
    boolean true if file was pushed successfully. false otherwise.

    Throws
    DeviceNotAvailableException

    pushFile

    boolean pushFile (File localFile, 
                    String remoteFilePath)

    Push a file to device

    Parameters
    localFile File: the local file to push

    remoteFilePath String: the remote destination absolute file path

    Returns
    boolean true if file was pushed successfully. false otherwise.

    Throws
    DeviceNotAvailableException

    pushString

    boolean pushString (String contents, 
                    String remoteFilePath)

    Push file created from a string to device

    Parameters
    contents String: the contents of the file to push

    remoteFilePath String: the remote destination absolute file path

    Returns
    boolean true if string was pushed successfully. false otherwise.

    Throws
    DeviceNotAvailableException

    reboot

    void reboot ()

    Reboots the device into adb mode.

    Blocks until device becomes available.

    Throws
    DeviceNotAvailableException

    rebootIntoBootloader

    void rebootIntoBootloader ()

    Reboots the device into bootloader mode.

    Blocks until device is in bootloader mode.

    Throws
    DeviceNotAvailableException
    UnsupportedOperationException

    rebootIntoRecovery

    void rebootIntoRecovery ()

    Reboots the device into adb recovery mode.

    Blocks until device enters recovery

    Throws
    DeviceNotAvailableException

    rebootUntilOnline

    void rebootUntilOnline ()

    An alternate to reboot() that only blocks until device is online ie visible to adb.

    Throws
    DeviceNotAvailableException

    recoverDevice

    void recoverDevice ()

    Attempts to recover device communication.

    Throws
    DeviceNotAvailableException if device is not longer available

    remountSystemWritable

    void remountSystemWritable ()

    Make the system partition on the device writable. May reboot the device.

    Throws
    DeviceNotAvailableException

    removeAdmin

    boolean removeAdmin (String componentName, 
                    int userId)

    Remove given device admin in given user and return true if it is successful, false otherwise.

    Parameters
    componentName String: of device admin to be removed.

    userId int: of user that the device admin lives in.

    Returns
    boolean True if it is successful, false otherwise.

    Throws
    DeviceNotAvailableException

    removeOwners

    void removeOwners ()

    Remove all existing device profile owners with the best effort.

    Throws
    DeviceNotAvailableException

    removeUser

    boolean removeUser (int userId)

    Remove a given user from the device.

    Parameters
    userId int: of the user to remove

    Returns
    boolean true if we were succesful in removing the user, false otherwise.

    Throws
    DeviceNotAvailableException

    runInstrumentationTests

    boolean runInstrumentationTests (IRemoteAndroidTestRunner runner, 
                    Collection<ITestRunListener> listeners)

    Runs instrumentation tests, and provides device recovery.

    If connection with device is lost before test run completes, and recovery succeeds, all listeners will be informed of testRunFailed and "false" will be returned. The test command will not be rerun. It is left to callers to retry if necessary.

    If connection with device is lost before test run completes, and recovery fails, all listeners will be informed of testRunFailed and DeviceNotAvailableException will be thrown.

    Parameters
    runner IRemoteAndroidTestRunner: the IRemoteAndroidTestRunner which runs the tests

    listeners Collection: the test result listeners

    Returns
    boolean true if test command completed. false if it failed to complete due to device communication exception, but recovery succeeded

    Throws
    DeviceNotAvailableException

    runInstrumentationTests

    boolean runInstrumentationTests (IRemoteAndroidTestRunner runner, 
                    ITestRunListener... listeners)

    Convenience method for performing runInstrumentationTests(IRemoteAndroidTestRunner, Collection) with one or more listeners passed as parameters.

    Parameters
    runner IRemoteAndroidTestRunner: the IRemoteAndroidTestRunner which runs the tests

    listeners ITestRunListener: the test result listener(s)

    Returns
    boolean true if test command completed. false if it failed to complete, but recovery succeeded

    Throws
    DeviceNotAvailableException

    runInstrumentationTestsAsUser

    boolean runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, 
                    int userId, 
                    ITestRunListener... listeners)

    Same as runInstrumentationTests(IRemoteAndroidTestRunner, ITestRunListener) but runs the test for a given user.

    Parameters
    runner IRemoteAndroidTestRunner

    userId int

    listeners ITestRunListener

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    runInstrumentationTestsAsUser

    boolean runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, 
                    int userId, 
                    Collection<ITestRunListener> listeners)

    Same as runInstrumentationTests(IRemoteAndroidTestRunner, Collection) but runs the test for the given user.

    Parameters
    runner IRemoteAndroidTestRunner

    userId int

    listeners Collection

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    setDate

    void setDate (Date date)

    Sets the date on device

    Note: setting date on device requires root

    Parameters
    date Date: specify a particular date; will use host date if null

    Throws
    DeviceNotAvailableException

    setDeviceOwner

    boolean setDeviceOwner (String componentName, 
                    int userId)

    Set a device admin component as device owner in given user.

    Parameters
    componentName String: of device admin to be device owner.

    userId int: of the user that the device owner lives in.

    Returns
    boolean True if it is successful, false otherwise.

    Throws
    DeviceNotAvailableException

    setDeviceState

    void setDeviceState (TestDeviceState deviceState)

    Update the device's state.

    Parameters
    deviceState TestDeviceState: the TestDeviceState

    setEmulatorOutputStream

    void setEmulatorOutputStream (SizeLimitedOutputStream output)

    For emulator set SizeLimitedOutputStream to log output

    Parameters
    output SizeLimitedOutputStream: to log the output

    setEmulatorProcess

    void setEmulatorProcess (Process p)

    Sets the Process, when this device is an emulator.

    Parameters
    p Process

    setFastbootEnabled

    void setFastbootEnabled (boolean fastbootEnabled)

    Set the fastboot option for the device. Should be set when device is first allocated.

    Parameters
    fastbootEnabled boolean: whether fastboot is available for the device or not

    setFastbootPath

    void setFastbootPath (String fastbootPath)

    Sets the path to the fastboot binary that should be used. Still requires isFastbootEnabled() to be true, to have fastboot functions enabled.

    Parameters
    fastbootPath String

    setIDevice

    void setIDevice (IDevice newDevice)

    Update the IDevice associated with this ITestDevice.

    The new IDevice must refer the same physical device as the current reference. This method will be called if DDMS has allocated a new IDevice

    Parameters
    newDevice IDevice: the IDevice

    setOptions

    void setOptions (TestDeviceOptions options)

    Set the TestDeviceOptions for the device

    Parameters
    options TestDeviceOptions

    setRecovery

    void setRecovery (IDeviceRecovery recovery)

    Set the IDeviceRecovery to use for this device. Should be set when device is first allocated.

    Parameters
    recovery IDeviceRecovery: the IDeviceRecovery

    setRecoveryMode

    void setRecoveryMode (ITestDevice.RecoveryMode mode)

    Set the current recovery mode to use for the device.

    Used to control what recovery method to use when a device communication problem is encountered. Its recommended to only use this method sparingly when needed (for example, when framework is down, etc

    Parameters
    mode ITestDevice.RecoveryMode: whether 'recover till online only' mode should be on or not.

    setSetting

    void setSetting (String namespace, 
                    String key, 
                    String value)

    See setSetting(int, String, String, String) and performed on system user.

    Parameters
    namespace String

    key String

    value String

    Throws
    DeviceNotAvailableException

    setSetting

    void setSetting (int userId, 
                    String namespace, 
                    String key, 
                    String value)

    Add a setting value to the namespace of a given user. Some settings will only be available after a reboot. namespace must be one of: {"system", "secure", "global"}

    Parameters
    userId int

    namespace String

    key String

    value String

    Throws
    DeviceNotAvailableException

    setUseFastbootErase

    void setUseFastbootErase (boolean useFastbootErase)

    Set whether to use fastboot erase or fastboot format to wipe a partition on the device.

    Parameters
    useFastbootErase boolean: true if fastboot erase should be used or false if fastboot format should be used.

    startLogcat

    void startLogcat ()

    Start capturing logcat output from device in the background.

    Will have no effect if logcat output is already being captured. Data can be later retrieved via getLogcat.

    When the device is no longer in use, stopLogcat() must be called.

    startLogcat() and stopLogcat() do not normally need to be called when within a TF invocation context, as the TF framework will start and stop logcat.

    startUser

    boolean startUser (int userId)

    Starts a given user in the background if it is currently stopped. If the user is already running in the background, this method is a NOOP.

    Parameters
    userId int: of the user to start in the background

    Returns
    boolean true if the user was successfully started in the background.

    Throws
    DeviceNotAvailableException

    stopEmulatorOutput

    void stopEmulatorOutput ()

    Close and delete the emulator output.

    stopLogcat

    void stopLogcat ()

    Stop capturing logcat output from device, and discard currently saved logcat data.

    Will have no effect if logcat output is not being captured.

    stopUser

    boolean stopUser (int userId)

    Stops a given user. If the user is already stopped, this method is a NOOP. Cannot stop current and system user.

    Parameters
    userId int: of the user to stop.

    Returns
    boolean true if the user was successfully stopped.

    Throws
    DeviceNotAvailableException

    stopUser

    boolean stopUser (int userId, 
                    boolean waitFlag, 
                    boolean forceFlag)

    Stop a given user. Possible to provide extra flags to wait for the operation to have effect, and force terminate the user. Cannot stop current and system user.

    Parameters
    userId int: of the user to stop.

    waitFlag boolean: will make the command wait until user is stopped.

    forceFlag boolean: will force stop the user.

    Returns
    boolean true if the user was successfully stopped.

    Throws
    DeviceNotAvailableException

    switchToAdbTcp

    String switchToAdbTcp ()

    Switch device to adb-over-tcp mode.

    Returns
    String the tcp serial number or null if device could not be switched

    Throws
    DeviceNotAvailableException

    switchToAdbUsb

    boolean switchToAdbUsb ()

    Switch device to adb over usb mode.

    Returns
    boolean true if switch was successful, false otherwise.

    Throws
    DeviceNotAvailableException

    switchUser

    boolean switchUser (int userId)

    Switch to another userId with a default timeout. switchUser(int, long).

    Parameters
    userId int

    Returns
    boolean True if the new userId matches the userId provider. False otherwise.

    Throws
    DeviceNotAvailableException

    switchUser

    boolean switchUser (int userId, 
                    long timeout)

    Switch to another userId with the provided timeout as deadline. Attempt to disable keyguard after user change is successful.

    Parameters
    userId int

    timeout long: to wait before returning false for switch-user failed.

    Returns
    boolean True if the new userId matches the userId provider. False otherwise.

    Throws
    DeviceNotAvailableException

    syncFiles

    boolean syncFiles (File localFileDir, 
                    String deviceFilePath)

    Incrementally syncs the contents of a local file directory to device.

    Decides which files to push by comparing timestamps of local files with their remote equivalents. Only 'newer' or non-existent files will be pushed to device. Thus overhead should be relatively small if file set on device is already up to date.

    Hidden files (with names starting with ".") will be ignored.

    Example usage: syncFiles("/tmp/files", "/sdcard") will created a /sdcard/files directory if it doesn't already exist, and recursively push the /tmp/files contents to /sdcard/files.

    Parameters
    localFileDir File: the local file directory containing files to recursively push.

    deviceFilePath String: the remote destination absolute file path root. All directories in thos file path must be readable. ie pushing to /data/local/tmp when adb is not root will fail

    Returns
    boolean true if files were synced successfully. false otherwise.

    Throws
    DeviceNotAvailableException

    takeBugreport

    Bugreport takeBugreport ()

    Take a bugreport and returns it inside a Bugreport object to handle it. Return null in case of issue.

    File referenced in the Bugreport object need to be cleaned via close().

    Returns
    Bugreport

    unencryptDevice

    boolean unencryptDevice ()

    Unencrypts the device.

    Unencrypting the device may cause device to be wiped and may reboot device. This method will block until device is available and ready for testing. Requires fastboot inorder to wipe the userdata partition.

    Returns
    boolean true if successful.

    Throws
    DeviceNotAvailableException
    UnsupportedOperationException

    uninstallPackage

    String uninstallPackage (String packageName)

    Uninstall an Android package from device.

    Parameters
    packageName String: the Android package to uninstall

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    unlockDevice

    boolean unlockDevice ()

    Unlocks the device if the device is in an encrypted state.

    This method may restart the framework but will not call postBootSetup(). Therefore, the device might not be fully ready to be tested when this method returns.

    Returns
    boolean true if successful or if the device is unencrypted.

    Throws
    DeviceNotAvailableException
    UnsupportedOperationException

    waitForBootComplete

    boolean waitForBootComplete (long timeOut)

    Blocks until the device's boot complete flag is set.

    Parameters
    timeOut long: time in msecs to wait for the flag to be set

    Returns
    boolean true if device's boot complete flag is set within the timeout

    Throws
    DeviceNotAvailableException

    waitForDeviceAvailable

    void waitForDeviceAvailable ()

    Waits for the device to be responsive and available for testing. Uses default timeout.

    Throws
    DeviceNotAvailableException

    waitForDeviceAvailable

    void waitForDeviceAvailable (long waitTime)

    Waits for the device to be responsive and available for testing.

    Parameters
    waitTime long: the time in ms to wait

    Throws
    DeviceNotAvailableException

    waitForDeviceInRecovery

    boolean waitForDeviceInRecovery (long waitTime)

    Blocks for the device to be in the 'adb recovery' state (note this is distinct from IDeviceRecovery).

    Parameters
    waitTime long: the time in ms to wait

    Returns
    boolean true if device boots into recovery before time expires. false otherwise

    waitForDeviceNotAvailable

    boolean waitForDeviceNotAvailable (long waitTime)

    Blocks for the device to be not available ie missing from adb

    Parameters
    waitTime long: the time in ms to wait

    Returns
    boolean true if device becomes not available before time expires. false otherwise

    waitForDeviceOnline

    void waitForDeviceOnline ()

    Blocks until device is visible via adb. Uses default timeout

    Note the device may not necessarily be responsive to commands on completion. Use waitForDeviceAvailable() instead.

    Throws
    DeviceNotAvailableException

    waitForDeviceOnline

    void waitForDeviceOnline (long waitTime)

    Blocks until device is visible via adb.

    Note the device may not necessarily be responsive to commands on completion. Use waitForDeviceAvailable() instead.

    Parameters
    waitTime long: the time in ms to wait

    Throws
    DeviceNotAvailableException

    waitForDeviceShell

    boolean waitForDeviceShell (long waitTime)

    Waits for device to be responsive to a basic adb shell command.

    Parameters
    waitTime long: the time in ms to wait

    Returns
    boolean true if device becomes responsive before waitTime elapses.

    Protected methods

    checkApiLevelAgainst

    void checkApiLevelAgainst (String feature, 
                    int strictMinLevel)

    Parameters
    feature String

    strictMinLevel int

    doAdbReboot

    void doAdbReboot (String into)

    Perform a adb reboot.

    Parameters
    into String: the bootloader name to reboot into, or null to just reboot the device.

    Throws
    DeviceNotAvailableException

    ensureRuntimePermissionSupported

    void ensureRuntimePermissionSupported ()

    helper method to throw exception if runtime permission isn't supported

    Throws
    DeviceNotAvailableException

    getBugreportzInternal

    File getBugreportzInternal ()

    Internal Helper method to get the bugreportz zip file as a File. Exposed for testing.

    Returns
    File

    getDeviceTimeOffset

    long getDeviceTimeOffset (Date date)

    Helper to get the time difference between the device and the host. Use Epoch time. Exposed for testing.

    Parameters
    date Date

    Returns
    long

    Throws
    DeviceNotAvailableException

    getRunUtil

    IRunUtil getRunUtil ()

    Get the RunUtil instance to use.

    Exposed for unit testing.

    Returns
    IRunUtil

    isNewer

    boolean isNewer (File localFile, 
                    IFileEntry entry)

    Return true if local file is newer than remote file. IFileEntry being accurate to the minute, in case of equal times, the file will be considered newer. Exposed for testing.

    Parameters
    localFile File

    entry IFileEntry

    Returns
    boolean

    performDeviceAction

    boolean performDeviceAction (String actionDescription, 
                    NativeDevice.DeviceAction action, 
                    int retryAttempts)

    Performs an action on this device. Attempts to recover device and optionally retry command if action fails.

    Parameters
    actionDescription String: a short description of action to be performed. Used for logging purposes only.

    action NativeDevice.DeviceAction: the action to be performed

    retryAttempts int: the retry attempts to make for action if it fails but recovery succeeds

    Returns
    boolean true if action was performed successfully

    Throws
    DeviceNotAvailableException if recovery attempt fails or max attempts done without success

    prePostBootSetup

    void prePostBootSetup ()

    Allows each device type (AndroidNativeDevice, TestDevice) to override this method for specific post boot setup.

    Throws
    DeviceNotAvailableException

    setLogStartDelay

    void setLogStartDelay (int delay)

    Sets the time in ms to wait before starting logcat capture for a online device.

    Parameters
    delay int: the delay in ms

    waitForDeviceNotAvailable

    void waitForDeviceNotAvailable (String operationDesc, 
                    long time)

    Parameters
    operationDesc String

    time long