NativeDevice
public class NativeDevice
extends Object implements IConfigurationReceiver , IManagedTestDevice , ITestLoggerReceiver
| java.lang.Object | |
| ↳ | com.android.tradefed.device.NativeDevice |
Реализация по умолчанию для тестового устройства ITestDevice Устройства Android без полного стека.
Краткое содержание
Вложенные классы | |
|---|---|
class | NativeDevice.AdbAction |
class | NativeDevice.AdbShellAction |
class | NativeDevice.RebootDeviceAction |
Константы | |
|---|---|
String | DEBUGFS_PATH |
int | INVALID_USER_IDВозвращаемое значение для любого недействительного/ненайденного идентификатора пользователя: UserHandle определил значение -10000. |
long | MAX_HOST_DEVICE_TIME_OFFSET |
int | MAX_RETRY_ATTEMPTSколичество попыток повторного выполнения команды по умолчанию |
String | SD_CARD |
String | STORAGE_EMULATED |
Поля | |
|---|---|
protected TestDeviceOptions | mOptions |
protected final IDeviceStateMonitor | mStateMonitor |
Государственные строители | |
|---|---|
NativeDevice ( IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor) Создает | |
Общедоступные методы | |
|---|---|
String | adbInstallPackage (File packageFile, boolean reinstall, String... extraArgs)Установите пакет Android на устройство с помощью команды adb. |
String | adbInstallPackage (File packageFile, boolean reinstall, boolean grantPermissions, String... extraArgs)Установите пакет Android на устройство с помощью команды adb. |
void | batchPrefetchStartupBuildProps ()Микрооптимизация (около 400 миллисекунд) достигается за счет предварительной загрузки всех необходимых свойств, вместо вызова команды 'adb getprop' для каждого из них. |
boolean | canSwitchToHeadlessSystemUser ()Возвращает значение, указывающее, разрешено ли переключение на пользователя SYSTEM без графического интерфейса. |
boolean | checkApiLevelAgainstNextRelease (int strictMinLevel)Проверьте, поддерживается ли функция в настоящее время на минимально поддерживаемом уровне. |
boolean | checkConnectivity ()Убедитесь, что устройство имеет доступ к сети. |
boolean | clearErrorDialogs ()Попробуйте закрыть все диалоговые окна с ошибками, отображаемые в данный момент в пользовательском интерфейсе устройства. |
void | clearLastConnectedWifiNetwork ()Удаляет последнюю подключенную сеть Wi-Fi. |
void | clearLogcat ()Удаляет все накопленные данные из logcat. |
IWifiHelper.WifiConnectionResult | connectToWifiNetworkIfNeededWithResult (String wifiSsid, String wifiPsk, boolean scanSsid) Вариант функции |
IWifiHelper.WifiConnectionResult | connectToWifiNetworkIfNeededWithResult (String wifiSsid, String wifiPsk) Вариант функции |
IWifiHelper.WifiConnectionResult | connectToWifiNetworkWithResult (String wifiSsid, String wifiPsk, boolean scanSsid)Подключается к сети Wi-Fi. |
IWifiHelper.WifiConnectionResult | connectToWifiNetworkWithResult (Map<String, String> wifiSsidToPsk)Подключается к сети Wi-Fi. |
IWifiHelper.WifiConnectionResult | connectToWifiNetworkWithResult (Map<String, String> wifiSsidToPsk, boolean scanSsid)Подключается к сети Wi-Fi. |
IWifiHelper.WifiConnectionResult | connectToWifiNetworkWithResult (String wifiSsid, String wifiPsk)Подключается к сети Wi-Fi. |
int | createUser (String name, boolean guest, boolean ephemeral)Создайте пользователя с заданным именем и указанными флагами. |
int | createUser (String name, boolean guest, boolean ephemeral, boolean forTesting)Создайте пользователя с заданным именем и указанными флагами. |
int | createUser (String name)Создайте пользователя с заданным именем и флагами по умолчанию, равными 0. |
int | createUserNoThrow (String name)Создайте пользователя с заданным именем и флагами по умолчанию, равными 0. |
DeviceInspectionResult | debugDeviceNotAvailable ()Проверяет устройство и предоставляет подробную информацию, когда устройство становится недоступным. |
void | deleteFile (String deviceFilePath, int userId)Вспомогательный метод для удаления файла или каталога на устройстве. |
void | deleteFile (String deviceFilePath)Вспомогательный метод для удаления файла или каталога на устройстве. |
void | deregisterDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver) Удаляет зарегистрированный |
boolean | deviceSoftRestarted ( ProcessInfo prevSystemServerProcess) Вспомогательный метод для проверки того, была ли выполнена программная перезагрузка устройства, путем сравнения текущего значения system_server с предыдущим значением system_server |
boolean | deviceSoftRestartedSince (long utcEpochTime, TimeUnit timeUnit) Вспомогательный метод для проверки того, было ли устройство перезагружено программно с момента начала эпохи UTC, указанного на устройстве, и его |
boolean | disableAdbRoot ()Отключает корневой доступ к adb. |
void | disableKeyguard ()Попытки отключить блокировку клавиатуры. |
boolean | disableNetworkMonitor ()Отключает мониторинг сети на устройстве. |
boolean | disconnectFromWifi ()Отключается от сети Wi-Fi. |
boolean | doesFileExist (String deviceFilePath, int userId)Вспомогательный метод для определения наличия файла на устройстве для данного пользователя. |
boolean | doesFileExist (String deviceFilePath)Вспомогательный метод для определения наличия файла на устройстве. |
File | dumpHeap (String process, String devicePath)Попытка дампа памяти кучи с сервера system_server. |
boolean | enableAdbRoot ()Включает root-доступ к adb. |
boolean | enableNetworkMonitor ()Включает мониторинг сети на устройстве. |
String | executeAdbCommand (long timeout, String... cmdArgs)Вспомогательный метод, который выполняет команду adb как системную команду с указанным таймаутом. |
String | executeAdbCommand (String... cmdArgs)Вспомогательный метод, выполняющий команду adb как системную команду. |
String | executeAdbCommand (long timeout, Map<String, String> envMap, String... cmdArgs)Вспомогательный метод, который выполняет команду adb как системную команду с указанным таймаутом. |
CommandResult | executeAdbV2Command (String... cmdArgs)Вспомогательный метод, выполняющий команду adb как системную команду. |
CommandResult | executeAdbV2Command (long timeout, String... cmdArgs)Вспомогательный метод, который выполняет команду adb как системную команду с указанным таймаутом. |
CommandResult | executeAdbV2Command (long timeout, Map<String, String> envMap, String... cmdArgs)Вспомогательный метод, который выполняет команду adb как системную команду с указанным таймаутом. |
CommandResult | executeAdbV2Command (long timeout, Map<String, String> envMap, int retryAttempts, String... cmdArgs)Вспомогательный метод, который выполняет команду adb как системную команду с указанным таймаутом. |
CommandResult | executeFastbootCommand (String... cmdArgs)Вспомогательный метод, который выполняет команду fastboot как системную команду с таймаутом по умолчанию в 2 минуты. |
CommandResult | executeFastbootCommand (long timeout, String... cmdArgs)Вспомогательный метод, который выполняет команду fastboot как системную команду. |
CommandResult | executeLongFastbootCommand (String... cmdArgs)Вспомогательный метод, который выполняет длительную команду fastboot в качестве системной команды. |
CommandResult | executeLongFastbootCommand (Map<String, String> envVarMap, String... cmdArgs)Вспомогательный метод, который выполняет длительную команду fastboot как системную команду с использованием системных переменных окружения. |
String | executeShellCommand (String command) Вспомогательный метод, который выполняет команду оболочки adb и возвращает результат в виде |
void | executeShellCommand (String command, IShellOutputReceiver receiver, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
void | executeShellCommand (String command, IShellOutputReceiver receiver, long maxTimeoutForCommand, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
void | executeShellCommand (String command, IShellOutputReceiver receiver)Выполняет заданную команду оболочки adb, повторяя попытку несколько раз в случае сбоя. |
CommandResult | executeShellV2Command (String cmd) Вспомогательный метод, который выполняет команду оболочки adb и возвращает результаты в виде |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
CommandResult | executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput) Вспомогательный метод, который выполняет команду оболочки adb и возвращает результаты в виде |
CommandResult | executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
CommandResult | executeShellV2Command (String cmd, OutputStream pipeToOutput) Вспомогательный метод, который выполняет команду оболочки adb и возвращает результаты в виде |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, long maxTimeoutForCommand, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды. |
CommandResult | executeShellV2Command (String cmd, IShellOutputReceiver receiver) Вспомогательный метод, который выполняет команду оболочки adb и возвращает результаты в виде |
CommandResult | fastbootOemRamdumpNow ()Вспомогательный метод, запускающий создание дампа оперативной памяти в режиме быстрой загрузки (fastboot). |
CommandResult | fastbootWipePartition (String partition)Вспомогательный метод, который очищает раздел на устройстве. |
Set< ITestDevice.ApexInfo > | getActiveApexes ()Получите информацию об активированных на устройстве APEX-серверах. |
String | getAdbPath ()Возвращает путь к используемому исполняемому файлу adb. |
Map<String, String> | getAllSettings (String namespace)Возвращает пары ключ-значение запрошенного пространства имен. |
DeviceAllocationState | getAllocationState ()Возвращает текущее состояние выделения ресурсов устройства. |
String | getAndroidId (int userId)Найдите и верните идентификатор Android, связанный с идентификатором пользователя (userId), в противном случае — значение null. |
Map<Integer, String> | getAndroidIds ()Создайте карту найденных идентификаторов Android, соответствующих идентификаторам пользователей. |
int | getApiLevel ()Получите уровень API устройства. |
int | getApiLevelFull () Аналогично функции |
PackageInfo | getAppPackageInfo (String packageName)Получить информацию об установленном на устройстве пакете. |
List< PackageInfo > | getAppPackageInfos ()Получить информацию об установленных на устройстве пакетах. |
String | getBasebandVersion ()Удобный способ получить базовую (радио) версию этого устройства. |
Integer | getBattery ()Возвращает текущий уровень заряда батареи устройства или значение Null, если уровень заряда батареи недоступен. |
boolean | getBooleanProperty (String name, boolean defaultValue)Возвращает логическое значение заданного свойства. |
Map<Long, String> | getBootHistory ()Вспомогательный метод собирает карту истории загрузки, содержащую время загрузки и причину загрузки. |
Map<Long, String> | getBootHistorySince (long utcEpochTime, TimeUnit timeUnit)Вспомогательный метод собирает карту истории загрузки, содержащую время загрузки и причину загрузки с момента начала эпохи на устройстве и в указанной единице времени. |
String | getBootloaderVersion ()Удобный способ получить версию загрузчика этого устройства. |
InputStreamSource | getBugreport ()Получает отчет об ошибке с устройства. |
InputStreamSource | getBugreportz ()Получает отчет об ошибке (ugreportz) с устройства. |
String | getBuildAlias ()Получите псевдоним сборки, которая в данный момент запущена на устройстве. |
String | getBuildFlavor ()Получите версию сборки для устройства. |
String | getBuildId ()Получите версию сборки, которая в данный момент установлена на устройстве. |
String | getBuildSigningKeys ()Возвращает тип ключа, использованного для подписи образа устройства. Как правило, устройства Android могут быть подписаны тестовыми ключами (как в AOSP) или ключами выпуска (контролируемыми отдельными производителями устройств). |
DeviceDescriptor | getCachedDeviceDescriptor () Возвращает кэшированный |
DeviceDescriptor | getCachedDeviceDescriptor (boolean shortDescriptor) Возвращает кэшированный |
String[] | getChildren (String path) Альтернатива использованию |
AbstractConnection | getConnection ()Текущее соединение, связанное с устройством. |
ContentProviderHandler | getContentProvider (int userId) Возвращает |
DeviceFoldableState | getCurrentFoldableState ()Возвращает текущее состояние складывания устройства или значение null, если возникли какие-либо проблемы. |
int | getCurrentUser ()Возвращает идентификатор текущего пользователя, выполняющего операцию. |
String | getDeviceClass ()Получите класс устройства. |
long | getDeviceDate ()Возвращает дату устройства в миллисекундах с начала эпохи. |
DeviceDescriptor | getDeviceDescriptor () Чтобы получить информацию об устройстве, не передавая сам объект устройства, верните |
DeviceDescriptor | getDeviceDescriptor (boolean shortDescriptor) Чтобы получить информацию об устройстве, не передавая сам объект устройства, верните |
TestDeviceState | getDeviceState ()Получите состояние устройства. |
long | getDeviceTimeOffset (Date date) Вспомогательная функция для получения разницы во времени между устройством и заданной |
InputStreamSource | getEmulatorOutput ()Получите поток стандартного вывода и стандартной ошибки эмулятора. |
Process | getEmulatorProcess () Возвращает |
final File | getExecuteShellCommandLog () Журнал, содержащий все записи выполнения команды |
long | getExternalStoreFreeSpace ()Вспомогательный метод для определения объема свободного места на внешнем накопителе устройства. |
String | getFastbootPath ()Возвращает путь к используемому исполняемому файлу fastboot. |
String | getFastbootProductType ()Удобный способ узнать тип продукта данного устройства, когда оно находится в режиме быстрой загрузки (fastboot). |
String | getFastbootProductVariant ()Удобный способ узнать тип продукта данного устройства, когда оно находится в режиме быстрой загрузки (fastboot). |
String | getFastbootSerialNumber ()Возвращает серийный номер режима fastboot. |
String | getFastbootVariable (String variableName)Получите заданное значение переменной fastboot с устройства. |
String | getFastbootVersion ()Возвращает строку версии используемого исполняемого файла fastboot. |
IFileEntry | getFileEntry (String path)Получить ссылку на удалённый файл на устройстве. |
IFileEntry | getFileEntry ( FileListingService.FileEntry entry) Неофициальный вспомогательный инструмент для получения объекта |
Set< DeviceFoldableState > | getFoldableStates ()Возвращает список состояний складывания устройства. |
IDevice | getIDevice () Возвращает ссылку на соответствующий |
Set<String> | getInstalledPackageNames ()Получите имена пакетов приложений, присутствующих на устройстве. |
long | getIntProperty (String name, long defaultValue)Возвращает целочисленное значение заданного свойства с устройства. |
String | getIpAddress ()Получает IP-адрес устройства. |
KeyguardControllerState | getKeyguardState ()Возвращает объект для получения текущего состояния блокировки клавиатуры или null, если это не поддерживается. |
long | getLastExpectedRebootTimeMillis () Возвращает значение в миллисекундах, указанное в результатах вызова функции |
int | getLaunchApiLevel ()Получите первый запущенный уровень API для устройства. |
InputStreamSource | getLogcat ()Получает моментальный поток данных из logcat. |
InputStreamSource | getLogcat (int maxBytes) Получает моментальный снимок потока последних |
InputStreamSource | getLogcatDump ()Получите дамп текущего лога logcat для устройства. |
InputStreamSource | getLogcatSince (long date)Получает поток моментальных снимков захваченных данных logcat, начиная с указанной даты. |
String | getMacAddress ()Возвращает MAC-адрес устройства, значение null, если запрос от устройства не удается. |
Integer | getMainUserId ()Возвращает основной идентификатор пользователя. |
Set<String> | getMainlineModuleInfo ()Получите информацию об основных модулях, установленных на устройстве. |
int | getMaxNumberOfRunningUsersSupported ()Получите максимальное количество поддерживаемых одновременно запущенных пользователей. |
int | getMaxNumberOfUsersSupported (String userType)Получите максимальное количество поддерживаемых пользователей заданного типа. |
int | getMaxNumberOfUsersSupported ()Получите максимальное количество поддерживаемых переключаемых пользователей, не считая гостей. |
Process | getMicrodroidProcess () |
IDeviceStateMonitor | getMonitor () Возвращает |
String | getMountPoint (String mountName)Возвращает точку монтирования. |
ITestDevice.MountPointInfo | getMountPointInfo (String mountpoint) Возвращает объект |
List< ITestDevice.MountPointInfo > | getMountPointInfo ()Возвращает разобранную версию информации из каталога /proc/mounts на устройстве. |
TestDeviceOptions | getOptions ()Получите параметры тестирования для устройства. |
long | getPartitionFreeSpace (String partition)Вспомогательный метод для определения объема свободного места на разделе устройства. |
Integer | getPrimaryUserId ()Возвращает основной идентификатор пользователя. |
ProcessInfo | getProcessByName (String processName) Вспомогательный метод выполняет команды "pidof" и "stat" и возвращает объект |
String | getProcessPid (String process)Возвращает PID сервиса или null, если что-то пошло не так. |
String | getProductType ()Удобный способ определения типа данного устройства. |
String | getProductVariant ()Удобный способ получения информации о варианте данного устройства. |
String | getProperty (String name)Получите заданное значение свойства с устройства. |
ITestDevice.RecoveryMode | getRecoveryMode ()Получите текущий режим восстановления, используемый на устройстве. |
int | getRemainingCreatableUserCount (String userType)Возвращает значение, указывающее, сколько пользователей заданного типа можно создать на этом устройстве. |
InputStreamSource | getScreenshot (Long displayId, String format, boolean rescale)Делает снимок экрана с устройства с заданным идентификатором дисплея в поддерживаемом формате. |
InputStreamSource | getScreenshot (String format)Делает снимок экрана с устройства. |
InputStreamSource | getScreenshot (long displayId)Делает снимок экрана с устройства, указанного в идентификаторе дисплея. |
InputStreamSource | getScreenshot (String format, boolean rescale)Делает снимок экрана с устройства. |
InputStreamSource | getScreenshot ()Делает снимок экрана с устройства. |
String | getSerialNumber ()Удобный способ получения серийного номера данного устройства. |
String | getSetting (int userId, String namespace, String key)Возвращает значение запрошенной настройки. |
String | getSetting (String namespace, String key) См. |
String | getSimOperator ()Возвращает имя оператора SIM-карты или null, если он недоступен или если устройство недоступно. |
String | getSimState ()Возвращает состояние SIM-карты или null, если оно недоступно или устройство недоступно. |
List<File> | getTombstones ()Получить и вернуть список надгробий с устройств. |
long | getTotalMemory ()Возвращает общий размер физической памяти в байтах или -1 в случае внутренней ошибки. |
String | getTrackingSerial ()Для целей управления устройством получите серийный номер, используемый для отслеживания устройства. |
Set<String> | getUninstallablePackageNames ()Получите список названий пакетов приложений, которые можно удалить. |
boolean | getUseFastbootErase ()Выясните, следует ли использовать fastboot erase или fastboot format для очистки раздела на устройстве. |
int | getUserFlags (int userId)Найти и вернуть флаги заданного пользователя. |
Map<Integer, UserInfo > | getUserInfos () Получает сопоставление useId и |
int | getUserSerialNumber (int userId)Возвращает серийный номер, связанный с userId, если он найден, -10000 в остальных случаях. |
int | getUserVisibleOnDisplay (int displayId)Получает идентификатор пользователя, видимого на заданном экране. |
IManagedTestDevice.DeviceEventResponse | handleAllocationEvent (DeviceEvent event)Обработайте указанное событие DeviceEvent. Обработайте событие DeviceEvent, которое может привести или не привести к переходу данного устройства в новое состояние выделения ресурсов. |
boolean | hasFeature (String feature)Проверьте, доступна ли данная функция на устройстве. |
void | initializeConnection ( IBuildInfo info, MultiMap <String, String> attributes)Инициализируйте соединение с устройством. |
String | installPackage (File packageFile, boolean reinstall, boolean grantPermissions, String... extraArgs)Установите пакет Android на устройство. |
String | installPackage (File packageFile, boolean reinstall, String... extraArgs)Установите пакет Android на устройство. |
String | installPackageForUser (File packageFile, boolean reinstall, boolean grantPermissions, int userId, String... extraArgs)Установить пакет Android на устройство для заданного пользователя. |
String | installPackageForUser (File packageFile, boolean reinstall, int userId, String... extraArgs)Установить пакет Android на устройство для заданного пользователя. |
boolean | installPackageWithIncrementalMode (File[] apkFiles, String[] extraArgs, String userId)Устанавливает APK-файлы в инкрементальном режиме. |
void | invalidatePropertyCache () |
boolean | isAdbRoot () |
boolean | isAdbTcp () |
boolean | isAppEnumerationSupported ()Проверьте, поддерживает ли платформа на устройстве перечисление приложений. |
boolean | isBypassLowTargetSdkBlockSupported ()Проверьте, поддерживает ли платформа на устройстве обход блокировки низкого уровня целевого SDK при установке приложений. |
boolean | isDebugfsMounted ()Проверьте, смонтирована ли файловая система debugfs. |
boolean | isDeviceEncrypted ()Возвращает значение, если устройство зашифровано. |
boolean | isDirectory (String path)Возвращает True, если путь на устройстве является каталогом, в противном случае — False. |
boolean | isEnableAdbRoot () |
boolean | isEncryptionSupported ()Возвращает значение, если на устройстве поддерживается шифрование. |
boolean | isExecutable (String fullPath)Возвращает True, если путь к файлу на устройстве ведет к исполняемому файлу, в противном случае — False. |
boolean | isFastbootEnabled ()Верните значение true, если для устройства доступна функция fastboot. |
boolean | isHeadless ()Возвращает true, если устройство работает в безэкранном режиме, false в противном случае. |
boolean | isHeadlessSystemUserMode ()Возвращает значение, указывающее, использует ли устройство безголовый пользовательский режим системы. |
boolean | isMainUserPermanentAdmin ()Возвращает значение, указывающее, является ли основной пользователь постоянным администратором и не может ли он быть удален или понижен в статусе до статуса, отличного от администратора. |
boolean | isMultiUserSupported ()Возвращает значение, указывающее, поддерживает ли данное устройство возможность переключения нескольких пользователей с собственным логином и настраиваемым рабочим пространством. |
boolean | isPackageInstalled (String packageName, String userId)Для проверки наличия установленного пакета для данного пользователя выполните запрос к устройству по заданному имени пакета и идентификатору пользователя. |
boolean | isPackageInstalled (String packageName)Чтобы проверить, установлен ли данный пакет на устройстве, выполните запрос по его имени. |
boolean | isRuntimePermissionSupported ()Проверьте, поддерживает ли платформа на устройстве предоставление разрешений во время выполнения. |
boolean | isShellV2Support () |
boolean | isStateBootloaderOrFastbootd () Возвращает true, если устройство находится в состоянии |
boolean | isUserRunning (int userId)Проверьте, запущен ли данный пользователь. |
boolean | isUserSecondary (int userId)Возвращает значение, указывающее, является ли указанный пользователь дополнительным пользователем в соответствии с его флагами. |
boolean | isUserVisible (int userId)Проверяет, виден ли данный пользователь. |
boolean | isUserVisibleOnDisplay (int userId, int displayId)Проверяет, виден ли данный пользователь на данном экране. |
boolean | isVisibleBackgroundUsersOnDefaultDisplaySupported () Возвращает значение, указывающее, разрешает ли устройство запуск пользователей в фоновом режиме в качестве видимых, в |
boolean | isVisibleBackgroundUsersSupported ()Возвращает значение, указывающее, разрешает ли устройство запуск пользователей в видимом режиме в фоновом режиме. |
boolean | isWifiEnabled ()Проверьте, включен ли Wi-Fi. |
Set<Long> | listDisplayIds ()Получите список идентификаторов доступных дисплеев на устройстве, предоставленный программой "dumpsys SurfaceFlinger". |
Set<Integer> | listDisplayIdsForStartingVisibleBackgroundUsers () Получает список дисплеев, которые можно использовать для |
ArrayList<Integer> | listUsers ()Получает список пользователей на устройстве. |
boolean | logAnrs ( ITestLogger logger)Собирает и регистрирует сигналы ANR с устройства. |
boolean | logBugreport (String dataName, ITestLogger listener)Вспомогательный метод для приема сообщения об ошибке и его отправки отправителям. |
void | logOnDevice (String tag, Log.LogLevel level, String format, Object... args)Записать сообщение в logcat устройства. |
void | mountDebugfs ()Смонтируйте debugfs. |
void | nonBlockingReboot ()Выдает команду на перезагрузку устройства и возвращает результат после завершения команды и когда устройство перестает быть видимым для adb. |
void | postAdbRootAction ()Укажите, если устройству необходимо выполнить определенные действия после получения root-прав по протоколу adb и до повторного подключения к сети. |
void | postAdbUnrootAction ()Укажите, если после выполнения команды adb unroot и до повторного подключения устройства к сети необходимо выполнить какие-либо определенные действия. |
void | postBootSetup ()Выполните инструкции по настройке устройства для проведения тестирования после каждой загрузки. |
void | postInvocationTearDown (Throwable exception)Дополнительные шаги для очистки, специфичные для конкретного устройства, будут выполнены после завершения вызова. |
void | preInvocationSetup ( IBuildInfo info, MultiMap <String, String> attributes)Дополнительные шаги для настройки, специфичной для конкретного устройства, которые будут выполнены на устройстве перед запуском процесса. |
boolean | pullDir (String deviceFilePath, File localDir, int userId)Рекурсивно извлекать содержимое каталога с устройства. |
boolean | pullDir (String deviceFilePath, File localDir)Рекурсивно извлекать содержимое каталога с устройства. |
boolean | pullDir (String deviceFilePath, File localDir, int userId, long timeout)Рекурсивно извлекать содержимое каталога с устройства. |
boolean | pullFile (String remoteFilePath, File localFile, int userId, long timeout)Извлекает файл с устройства. |
boolean | pullFile (String remoteFilePath, File localFile)Извлекает файл с устройства. |
File | pullFile (String remoteFilePath, int userId) Извлекает файл с устройства, сохраняет его во временном локальном |
File | pullFile (String remoteFilePath) Извлекает файл с устройства, сохраняет его во временном локальном |
boolean | pullFile (String remoteFilePath, File localFile, int userId)Извлекает файл с устройства. |
String | pullFileContents (String remoteFilePath)Извлекает файл с устройства и возвращает его содержимое. |
File | pullFileFromExternal (String remoteFilePath) Удобный метод для извлечения файла из внешнего хранилища устройства, сохранения его во временном локальном |
boolean | pushDir (File localFileDir, String deviceFilePath, int userId)Рекурсивно загружать содержимое каталога на устройство. |
boolean | pushDir (File localFileDir, String deviceFilePath, Set<String> excludedDirectories)Рекурсивно передавать содержимое каталога на устройство, исключая при этом некоторые отфильтрованные каталоги. |
boolean | pushDir (File localFileDir, String deviceFilePath)Рекурсивно загружать содержимое каталога на устройство. |
boolean | pushFile (File localFile, String remoteFilePath, boolean evaluateContentProviderNeeded) Вариант функции |
boolean | pushFile (File localFile, String remoteFilePath)Загрузите файл на устройство. |
boolean | pushFile (File localFile, String remoteFilePath, int userId)Загрузите файл на устройство. |
boolean | pushString (String contents, String remoteFilePath)Передайте файл, созданный из строки, на устройство. |
void | reboot (String reason) Перезагружает устройство в режим adb с указанной |
String | reboot (String command, String reason) Перезагружает устройство с помощью указанной |
void | reboot ()Перезагружает устройство в режим adb. |
void | rebootIntoBootloader ()Перезагружает устройство в режим загрузчика. |
void | rebootIntoFastbootd ()Перезагружает устройство в режим fastbootd. |
void | rebootIntoRecovery ()Перезагружает устройство в режим восстановления adb. |
void | rebootIntoSideload ()Перезагружает устройство в режим adb sideload (обратите внимание, что это специальный режим в режиме восстановления). Блокировка до тех пор, пока устройство не перейдет в режим боковой загрузки. |
void | rebootIntoSideload (boolean autoReboot)Перезагружает устройство в режим adb sideload (обратите внимание, что это специальный режим в режиме восстановления). Блокировка до тех пор, пока устройство не перейдет в режим боковой загрузки. |
void | rebootUntilOnline () Альтернатива функции |
void | rebootUntilOnline (String reason) Альтернатива функции |
void | rebootUserspace ()Перезагружает только пользовательскую часть устройства. |
void | rebootUserspaceUntilOnline () Альтернатива функции |
boolean | recoverDevice ()Попытки восстановить связь между устройством и устройством. |
void | registerDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver) Регистрирует объект |
void | remountSystemReadOnly ()Сделайте системный раздел на устройстве доступным только для чтения. |
void | remountSystemWritable ()Сделайте системный раздел на устройстве доступным для записи. |
void | remountVendorReadOnly ()Сделайте раздел производителя на устройстве доступным только для чтения. |
void | remountVendorWritable ()Сделайте раздел производителя на устройстве доступным для записи. |
boolean | removeAdmin (String componentName, int userId) Удалить администратора устройства у указанного пользователя и вернуть |
void | removeOwners ()Приложите все усилия для удаления всех существующих владельцев профилей устройств. |
boolean | removeUser (int userId)Удалить указанного пользователя с устройства. |
void | resetContentProviderSetup ()Чтобы снова запустить процесс, сбросьте флаг для настройки поставщика контента. |
boolean | runInstrumentationTests ( IRemoteAndroidTestRunner runner, Collection< ITestLifeCycleReceiver > listeners)Выполняет инструментальные тесты и обеспечивает восстановление устройства. |
boolean | runInstrumentationTests ( IRemoteAndroidTestRunner runner, ITestLifeCycleReceiver... listeners) Вспомогательный метод для выполнения |
boolean | runInstrumentationTestsAsUser ( IRemoteAndroidTestRunner runner, int userId, Collection< ITestLifeCycleReceiver > listeners) Аналогично методу |
boolean | runInstrumentationTestsAsUser ( IRemoteAndroidTestRunner runner, int userId, ITestLifeCycleReceiver... listeners) Аналогично |
void | setAdbPath (String adbPath)Задает путь к исполняемому файлу adb, который следует использовать. |
void | setConfiguration ( IConfiguration configuration) Внедряет используемый объект |
final void | setConnectionAvdInfo ( GceAvdInfo avdInfo) |
void | setDate (Date date)Устанавливает дату на устройстве. Примечание: для установки даты на устройстве требуются права root. |
boolean | setDeviceOwner (String componentName, int userId)Назначьте компонент администрирования устройства владельцем устройства для указанного пользователя. |
void | setDeviceState ( TestDeviceState deviceState)Обновите состояние устройства. |
void | setEmulatorOutputStream ( SizeLimitedOutputStream output) Для эмулятора установите |
void | setEmulatorProcess (Process p) Задает |
void | setFastbootEnabled (boolean fastbootEnabled)Установите параметр fastboot для устройства. |
void | setFastbootPath (String fastbootPath)Задает путь к исполняемому файлу fastboot, который следует использовать. |
void | setIDevice ( IDevice newDevice)Обновите IDevice, связанный с этим ITestDevice. |
void | setLogStartDelay (int delay)Устанавливает время в миллисекундах, которое необходимо подождать перед началом захвата логов с устройства, находящегося в сети. |
void | setOptions ( TestDeviceOptions options) Задайте параметры |
boolean | setProperty (String propKey, String propValue)Устанавливает заданное значение свойства на устройстве. |
void | setRecovery ( IDeviceRecovery recovery) Укажите |
void | setRecoveryMode ( ITestDevice.RecoveryMode mode)Установите текущий режим восстановления, который будет использоваться для устройства. |
void | setSetting (String namespace, String key, String value) См. |
void | setSetting (int userId, String namespace, String key, String value)Добавить значение параметра в пространство имен заданного пользователя. |
void | setTestLogger ( ITestLogger testLogger) Внедряет экземпляр |
void | setTrackingSerial (String trackingSerial)Для целей управления устройством мы отслеживаем серийный номер, который используем для ссылки на устройство. |
void | setUseFastbootErase (boolean useFastbootErase)Укажите, следует ли использовать команду fastboot erase или fastboot format для очистки раздела на устройстве. |
void | startLogcat ()Начать захват вывода logcat с устройства в фоновом режиме. |
boolean | startTradeInModeTesting (int timeoutMs)Включите тестовый режим обмена. |
boolean | startUser (int userId)Запускает заданного пользователя в фоновом режиме, если он в данный момент остановлен. |
boolean | startUser (int userId, boolean waitFlag)Запускает заданного пользователя в фоновом режиме, если он в данный момент остановлен. |
boolean | startVisibleBackgroundUser (int userId, int displayId, boolean waitFlag)Запускает пользователя в фоновом режиме, делая его видимым на указанном экране (т.е. позволяя пользователю запускать действия на этом экране). |
void | stopEmulatorOutput ()Закройте и удалите вывод эмулятора. |
void | stopLogcat ()Прекратите сбор данных logcat с устройства и удалите сохраненные данные logcat. |
void | stopTradeInModeTesting ()Прекратите тестирование режима обмена. |
boolean | stopUser (int userId)Останавливает определенного пользователя. |
boolean | stopUser (int userId, boolean waitFlag, boolean forceFlag)Остановить определенного пользователя. |
String | switchToAdbTcp ()Переключите устройство в режим adb-over-tcp. |
boolean | switchToAdbUsb ()Переключите устройство в режим ADB через USB. |
boolean | switchUser (int userId)Переключиться на другой идентификатор пользователя с таймаутом по умолчанию. |
boolean | switchUser (int userId, long timeout)Переключитесь на другой идентификатор пользователя, указав в качестве крайнего срока время ожидания. |
boolean | syncFiles (File localFileDir, String deviceFilePath)Постепенная синхронизация содержимого локального файлового каталога с устройством. |
Bugreport | takeBugreport () Принимает сообщение об ошибке и возвращает его в виде объекта |
String | uninstallPackage (String packageName)Удалите пакет Android с устройства. |
String | uninstallPackageForUser (String packageName, int userId)Удалить пакет Android с устройства для конкретного пользователя. |
boolean | unlockDevice ()Разблокирует устройство, если оно находится в зашифрованном состоянии. |
void | unmountDebugfs ()Отключите debugfs. |
boolean | waitForBootComplete (long timeOut)Блокировка выполняется до тех пор, пока не будет установлен флаг завершения загрузки устройства. |
boolean | waitForDeviceAvailable ()Ожидает, пока устройство станет отзывчивым и доступным для тестирования. |
boolean | waitForDeviceAvailable (long waitTime)Ожидает, пока устройство станет отзывчивым и доступным для тестирования. |
boolean | waitForDeviceAvailableInRecoverPath (long waitTime)Ожидает, пока устройство станет доступным и ответит на запросы, не рассматривая путь восстановления. |
void | waitForDeviceBootloader ()Блокировка выполняется до тех пор, пока устройство не станет видимым через fastboot. |
void | waitForDeviceFastbootD () |
boolean | waitForDeviceInRecovery (long waitTime) Блоки, позволяющие устройству находиться в состоянии «adb recovery» (обратите внимание, что это отличается от |
boolean | waitForDeviceInSideload (long waitTime)Блоки, позволяющие устройству находиться в состоянии "adb sideload". |
boolean | waitForDeviceNotAvailable (long waitTime)Блоки, необходимые для работы устройства, могут быть недоступны, то есть отсутствовать в adb. |
void | waitForDeviceOnline ()Блокировка продолжается до тех пор, пока устройство не станет видимым через adb. |
void | waitForDeviceOnline (long waitTime)Блокировка продолжается до тех пор, пока устройство не станет видимым через adb. |
boolean | waitForDeviceShell (long waitTime)Ожидает, пока устройство ответит на базовую команду оболочки adb. |
Защищенные методы | |
|---|---|
void | addExtraConnectionBuilderArgs ( DefaultConnection.ConnectionBuilder builder) |
String[] | buildAdbShellCommand (String command, boolean forceExitStatusDetection, boolean oldShellCommand)Создает команду операционной системы для заданной сессии командной оболочки adb и аргументов. |
void | checkApiLevelAgainst (String feature, int strictMinLevel) |
NativeDevice.RebootDeviceAction | createRebootDeviceAction ( NativeDevice.RebootMode rebootMode, String reason) Создайте объект |
IRunUtil | createRunUtil () |
void | doAdbReboot ( NativeDevice.RebootMode rebootMode, String reason)Выполните команду adb reboot. |
void | ensureRuntimePermissionSupported ()Вспомогательный метод для генерации исключения, если разрешение во время выполнения не поддерживается. |
int | getApiLevelSafe () |
ITestLogger | getLogger () |
IRunUtil | getRunUtil () Получите экземпляр |
String | internalGetProperty (String propName, String fastbootVar, String description)Получает свойство устройства из кэша ddmlib по умолчанию, а в случае отказа используется либо `adb shell getprop`, либо `fastboot getvar` в зависимости от того, находится ли устройство в режиме Fastboot или нет. |
boolean | isInRebootCallback ()Возвращает значение, указывающее, выполняется ли в данный момент функция обратного вызова перезагрузки. |
boolean | isNewer (File localFile, IFileEntry entry) Возвращает |
void | notifyRebootEnded () Уведомляет все |
void | notifyRebootStarted () Уведомляет все |
boolean | performDeviceAction (String actionDescription, NativeDevice.DeviceAction action, int retryAttempts)Выполняет действие над этим устройством. |
void | postAdbReboot ( NativeDevice.RebootMode rebootMode)Возможные дополнительные действия, которые можно предпринять после перезагрузки. |
void | prePostBootSetup ()Позволяет каждому типу устройства (AndroidNativeDevice, TestDevice) переопределить этот метод для конкретных настроек после загрузки. |
boolean | pullFileWithAdbCommand (String remoteFilePath, File localFile, long timeout) |
void | setClock (Clock clock)Укажите экземпляр Clock для использования. |
void | setMicrodroidProcess (Process process)Помечает тестовое устройство как microdroid и устанавливает его CID. |
void | setTestDeviceOptions (Map<String, String> deviceOptions) |
CommandResult | simpleFastbootCommand (long timeout, String[] fullCmd)Выполняет простую команду fastboot и сообщает о состоянии этой команды. |
CommandResult | simpleFastbootCommand (long timeout, Map<String, String> envVarMap, String[] fullCmd)Выполняет простую команду fastboot с использованием переменных окружения и сообщает о состоянии выполнения команды. |
boolean | waitForDeviceNotAvailable (String operationDesc, long time)Дождитесь, пока устройство не станет недоступным (прекратится отправка данных в adb). |
Константы
DEBUGFS_PATH
public static final String DEBUGFS_PATH
Постоянное значение: "/sys/kernel/debug"
INVALID_USER_ID
public static final int INVALID_USER_ID
Возвращаемое значение для любого недействительного/ненайденного идентификатора пользователя: UserHandle определил значение -10000.
Постоянное значение: -10000 (0xffffd8f0)
MAX_HOST_DEVICE_TIME_OFFSET
protected static final long MAX_HOST_DEVICE_TIME_OFFSET
Постоянное значение: 5000 (0x0000000000001388)
MAX_RETRY_ATTEMPTS
protected static final int MAX_RETRY_ATTEMPTS
количество попыток повторного выполнения команды по умолчанию
Постоянное значение: 2 (0x00000002)
SD-карта
protected static final String SD_CARD
Постоянное значение: "/sdcard/"
STORAGE_EMULATED
protected static final String STORAGE_EMULATED
Постоянное значение: "/storage/emulated/"
Поля
mOptions
protected TestDeviceOptions mOptions
mStateMonitor
protected final IDeviceStateMonitor mStateMonitor
Государственные строители
NativeDevice
public NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)
Создает TestDevice .
| Параметры | |
|---|---|
device | IDevice : связанный IDevice |
stateMonitor | IDeviceStateMonitor : механизм IDeviceStateMonitor для использования. |
allocationMonitor | IDeviceMonitor : объект IDeviceMonitor , информирующий об изменениях состояния выделенной памяти. Может быть равен null. |
Общедоступные методы
adbInstallPackage
public String adbInstallPackage (File packageFile,
boolean reinstall,
String... extraArgs)Установите пакет Android на устройство с помощью команды adb.
| Параметры | |
|---|---|
packageFile | File : APK-файл для установки |
reinstall | boolean : true если необходимо выполнить переустановку. |
extraArgs | String : необязательные дополнительные аргументы для передачи. См. 'adb shell pm -h' для получения информации о доступных параметрах. |
| Возвраты | |
|---|---|
String | String с кодом ошибки или null в случае успеха. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
adbInstallPackage
public String adbInstallPackage (File packageFile,
boolean reinstall,
boolean grantPermissions,
String... extraArgs)Установите пакет Android на устройство с помощью команды adb.
Примечание: Вызов этой функции допустим только в тех случаях, когда требуется явное управление предоставлением разрешений во время выполнения при установке.
| Параметры | |
|---|---|
packageFile | File : APK-файл для установки |
reinstall | boolean : true если необходимо выполнить переустановку. |
grantPermissions | boolean : должно ли быть предоставлено все разрешения во время выполнения при установке. |
extraArgs | String : необязательные дополнительные аргументы для передачи. См. 'adb shell pm -h' для получения информации о доступных параметрах. |
| Возвраты | |
|---|---|
String | String с кодом ошибки или null в случае успеха. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
batchPrefetchStartupBuildProps
public void batchPrefetchStartupBuildProps ()
Микрооптимизация (около 400 миллисекунд) достигается за счет предварительной загрузки всех необходимых свойств вместо вызова `adb getprop` для каждого из них. То есть, загрузка всех свойств происходит так же быстро, как и загрузка одного. Такие функции, как `device.getApiLevel()`, `checkApiLevelAgainstNextRelease` и `getBuildAlias`, вызывают `adb getprop` внутри. Мы же загружаем их за один вызов и вызываем `NativeDevice.setProperty`. Даже если мы этого не сделаем, NativeDevice сам вызовет `setProperty` и сохранит результат для последующих вызовов. Мы просто делаем это немного раньше. Если устройство находится в режиме восстановления или возникают другие ошибки при загрузке свойств, мы просто игнорируем их.
canSwitchToHeadlessSystemUser
public boolean canSwitchToHeadlessSystemUser ()
Возвращает значение, указывающее, разрешено ли переключение на пользователя SYSTEM без графического интерфейса.
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
проверкаApiLevelAgainstNextRelease
public boolean checkApiLevelAgainstNextRelease (int strictMinLevel)
Проверяет, поддерживается ли функция в настоящее время на минимально поддерживаемом уровне. Этот метод учитывает еще не выпущенные функции, до повышения уровня API.
| Параметры | |
|---|---|
strictMinLevel | int : Строго минимальный возможный уровень поддержки данной функции. |
| Возвраты | |
|---|---|
boolean | Значение True, если уровень поддерживается. В противном случае — False. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
проверка подключения
public boolean checkConnectivity ()
Убедитесь, что устройство имеет доступ к сети.
| Возвраты | |
|---|---|
boolean | Возвращает true , если устройство имеет работающее сетевое соединение, в противном случае false . |
| Броски | |
|---|---|
DeviceNotAvailableException | |
clearErrorDialogs
public boolean clearErrorDialogs ()
Попробуйте закрыть все диалоговые окна с ошибками, отображаемые в данный момент в пользовательском интерфейсе устройства.
| Возвраты | |
|---|---|
boolean | true , если диалоговые окна отсутствуют или успешно очищены. В противном случае false . |
| Броски | |
|---|---|
DeviceNotAvailableException | |
clearLastConnectedWifiNetwork
public void clearLastConnectedWifiNetwork ()
Очищает последнюю подключенную сеть Wi-Fi. Эту функцию следует вызывать при запуске нового вызова, чтобы избежать подключения к сети Wi-Fi, использованной в предыдущем тесте, после перезагрузки устройства.
clearLogcat
public void clearLogcat ()
Удаляет все накопленные данные из logcat.
Это полезно в тех случаях, когда необходимо убедиться, чтоITestDevice.getLogcat() возвращает только данные журнала, созданные после определенного момента (например, после прошивки новой версии устройства и т. д.). При необходимости подключитесь к сети Wi-Fi с результатом.
public IWifiHelper.WifiConnectionResult connectToWifiNetworkIfNeededWithResult (String wifiSsid, String wifiPsk, boolean scanSsid)
Вариант функции connectToWifiNetwork(String,String) , который подключается только в том случае, если устройство в данный момент не имеет доступа к сети.
| Параметры | |
|---|---|
scanSsid | boolean : следует ли сканировать скрытые SSID для этой сети. |
| Возвраты | |
|---|---|
IWifiHelper.WifiConnectionResult | Объект WifiConnectionResult указывает на состояние соединения. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
При необходимости подключитесь к сети Wi-Fi с результатом.
public IWifiHelper.WifiConnectionResult connectToWifiNetworkIfNeededWithResult (String wifiSsid, String wifiPsk)
Вариант функции connectToWifiNetwork(String,String) , который подключается только в том случае, если устройство в данный момент не имеет доступа к сети.
| Возвраты | |
|---|---|
IWifiHelper.WifiConnectionResult | Объект WifiConnectionResult указывает на состояние соединения. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
connectToWifiNetworkWithResult
public IWifiHelper.WifiConnectionResult connectToWifiNetworkWithResult (String wifiSsid, String wifiPsk, boolean scanSsid)
Подключается к сети Wi-Fi.
Включает Wi-Fi и блокирует соединение до тех пор, пока не будет установлено успешное соединение с указанной сетью Wi-Fi. После установления соединения экземпляр будет пытаться восстановить соединение после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork() .
| Параметры | |
|---|---|
wifiSsid | String : SSID сети Wi-Fi для подключения |
wifiPsk | String : парольная фраза PSK или null, если не зашифровано. |
scanSsid | boolean : следует ли сканировать скрытые SSID для этой сети. |
| Возвраты | |
|---|---|
IWifiHelper.WifiConnectionResult | Объект WifiConnectionResult указывает на состояние соединения. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
connectToWifiNetworkWithResult
public IWifiHelper.WifiConnectionResult connectToWifiNetworkWithResult (Map<String, String> wifiSsidToPsk)
Подключается к сети Wi-Fi.
Включает Wi-Fi и блокирует выполнение до тех пор, пока не будет установлено успешное соединение с одной из сетей Wi-Fi, указанных в карте wifiSsidToPsk. После установления соединения экземпляр будет пытаться восстановить соединение после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork() .
| Параметры | |
|---|---|
wifiSsidToPsk | Map : Карта соответствия SSID сетей Wi-Fi и паролей. |
| Возвраты | |
|---|---|
IWifiHelper.WifiConnectionResult | Объект WifiConnectionResult указывает на состояние соединения. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
connectToWifiNetworkWithResult
public IWifiHelper.WifiConnectionResult connectToWifiNetworkWithResult (Map<String, String> wifiSsidToPsk, boolean scanSsid)
Подключается к сети Wi-Fi.
Включает Wi-Fi и блокирует выполнение до тех пор, пока не будет установлено успешное соединение с одной из сетей Wi-Fi, указанных в карте wifiSsidToPsk. После установления соединения экземпляр будет пытаться восстановить соединение после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork() .
| Параметры | |
|---|---|
wifiSsidToPsk | Map : Карта соответствия SSID сетей Wi-Fi и паролей. |
scanSsid | boolean : следует ли сканировать скрытые SSID для этой сети. |
| Возвраты | |
|---|---|
IWifiHelper.WifiConnectionResult | Объект WifiConnectionResult указывает на состояние соединения. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
connectToWifiNetworkWithResult
public IWifiHelper.WifiConnectionResult connectToWifiNetworkWithResult (String wifiSsid, String wifiPsk)
Подключается к сети Wi-Fi.
Включает Wi-Fi и блокирует соединение до тех пор, пока не будет установлено успешное соединение с указанной сетью Wi-Fi. После установления соединения экземпляр будет пытаться восстановить соединение после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork() .
| Параметры | |
|---|---|
wifiSsid | String : SSID сети Wi-Fi для подключения |
wifiPsk | String : парольная фраза PSK или null, если не зашифровано. |
| Возвраты | |
|---|---|
IWifiHelper.WifiConnectionResult | Объект WifiConnectionResult указывает на состояние соединения. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
создать пользователя
public int createUser (String name,
boolean guest,
boolean ephemeral)Создайте пользователя с заданным именем и указанными флагами.
| Параметры | |
|---|---|
name | String : имя пользователя, которое нужно создать на устройстве. |
guest | boolean : включить флаг пользователя --guest при создании |
ephemeral | boolean : включить пользовательский флаг --ephemeral при создании |
| Возвраты | |
|---|---|
int | идентификатор созданного пользователя |
| Броски | |
|---|---|
DeviceNotAvailableException | |
IllegalStateException | |
создать пользователя
public int createUser (String name,
boolean guest,
boolean ephemeral,
boolean forTesting)Создайте пользователя с заданным именем и указанными флагами.
| Параметры | |
|---|---|
name | String : имя пользователя, которое нужно создать на устройстве. |
guest | boolean : включить флаг пользователя --guest при создании |
ephemeral | boolean : включить пользовательский флаг --ephemeral при создании |
forTesting | boolean : включить флаг тестирования --for-testing во время создания |
| Возвраты | |
|---|---|
int | идентификатор созданного пользователя |
| Броски | |
|---|---|
DeviceNotAvailableException | |
IllegalStateException | |
создать пользователя
public int createUser (String name)
Создайте пользователя с заданным именем и флагами по умолчанию, равными 0.
| Параметры | |
|---|---|
name | String : имя пользователя, которое нужно создать на устройстве. |
| Возвраты | |
|---|---|
int | целое число, обозначающее созданный идентификатор пользователя |
| Броски | |
|---|---|
DeviceNotAvailableException | |
IllegalStateException | |
createUserNoThrow
public int createUserNoThrow (String name)
Создайте пользователя с заданным именем и флагами по умолчанию, равными 0.
| Параметры | |
|---|---|
name | String : имя пользователя, которое нужно создать на устройстве. |
| Возвраты | |
|---|---|
int | Целочисленное значение, обозначающее созданный идентификатор пользователя, или -1 в случае ошибки. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
debugDeviceNotAvailable
public DeviceInspectionResult debugDeviceNotAvailable ()
Проверяет устройство и предоставляет подробную информацию, когда устройство становится недоступным.
| Возвраты | |
|---|---|
DeviceInspectionResult | |
удалитьФайл
public void deleteFile (String deviceFilePath,
int userId)Вспомогательный метод для удаления файла или каталога на устройстве.
| Параметры | |
|---|---|
deviceFilePath | String : Абсолютный путь к файлу на устройстве. |
userId | int : Идентификатор пользователя, которого нужно удалить. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
удалитьФайл
public void deleteFile (String deviceFilePath)
Вспомогательный метод для удаления файла или каталога на устройстве.
| Параметры | |
|---|---|
deviceFilePath | String : Абсолютный путь к файлу на устройстве. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
deregisterDeviceActionReceiver
public void deregisterDeviceActionReceiver (IDeviceActionReceiver deviceActionReceiver)
Удаляет зарегистрированный IDeviceActionReceiver .
| Параметры | |
|---|---|
deviceActionReceiver | IDeviceActionReceiver : Объект IDeviceActionReceiver , который будет удален. |
deviceSoftRestarted
public boolean deviceSoftRestarted (ProcessInfo prevSystemServerProcess)
Вспомогательный метод для проверки того, была ли выполнена программная перезагрузка устройства, путем сравнения текущего system_server с предыдущим system_server ProcessInfo . Используйте getProcessByName(String) для получения ProcessInfo .
| Параметры | |
|---|---|
prevSystemServerProcess | ProcessInfo : предыдущий процесс system_server ProcessInfo . |
| Возвраты | |
|---|---|
boolean | true если устройство было перезагружено программно. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
deviceSoftRestartedSince
public boolean deviceSoftRestartedSince (long utcEpochTime,
TimeUnit timeUnit)Вспомогательный метод для проверки того, была ли выполнена мягкая перезагрузка устройства с момента начала эпохи UTC, указанного на устройстве, и его TimeUnit . Мягкая перезагрузка означает перезапуск системного сервера вне рамок жесткой перезагрузки устройства (например, запрошенной перезагрузки). Текущее время UTC EpochTime устройства в миллисекундах можно получить с помощью метода getDeviceDate() .
| Параметры | |
|---|---|
utcEpochTime | long : время работы устройства в секундах с начала эпохи. |
timeUnit | TimeUnit : единица измерения времени TimeUnit для заданного времени utcEpochTime. |
| Возвраты | |
|---|---|
boolean | true если устройство было перезагружено программно. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
disableAdbRoot
public boolean disableAdbRoot ()
Отключает корневой доступ к adb.
Отключение корневого каталога adb может привести к отключению устройства от adb. Этот метод будет блокировать соединение до тех пор, пока устройство не станет доступным.| Возвраты | |
|---|---|
boolean | true если успех. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
disableKeyguard
public void disableKeyguard ()
Попытки отключить блокировку клавиатуры.
Сначала дождитесь готовности обработки ввода, это происходит примерно в то же время, когда устройство сообщает о завершении загрузки (BOOT_COMPLETE), по-видимому, асинхронно, поскольку в текущей реализации фреймворка иногда возникают состояния гонки. Затем отправляется команда на закрытие блокировки экрана (работает только с небезопасными блокировками).
| Броски | |
|---|---|
DeviceNotAvailableException | |
отключить сетевой монитор
public boolean disableNetworkMonitor ()
Отключает мониторинг сети на устройстве.
| Возвраты | |
|---|---|
boolean | true , если мониторинг успешно отключен. false если отключение не удалось. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
отключиться от Wi-Fi
public boolean disconnectFromWifi ()
Отключается от сети Wi-Fi.
Удаляет все сети из списка известных сетей и отключает Wi-Fi.| Возвраты | |
|---|---|
boolean | true , если отключение от сети Wi-Fi прошло успешно. false если отключение не удалось. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
doesFileExist
public boolean doesFileExist (String deviceFilePath,
int userId)Вспомогательный метод для определения наличия файла на устройстве для данного пользователя.
| Параметры | |
|---|---|
deviceFilePath | String : абсолютный путь к файлу на устройстве для проверки. |
userId | int : Идентификатор пользователя, по которому проверяется существование файла. |
| Возвраты | |
|---|---|
boolean | true если файл существует, false в противном случае. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
doesFileExist
public boolean doesFileExist (String deviceFilePath)
Helper method to determine if file on device exists.
| Параметры | |
|---|---|
deviceFilePath | String : the absolute path of file on device to check |
| Возвраты | |
|---|---|
boolean | true if file exists, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
dumpHeap
public File dumpHeap (String process,
String devicePath)Attempt to dump the heap from the system_server. It is the caller responsibility to clean up the dumped file.
| Параметры | |
|---|---|
process | String : the name of the device process to dumpheap on. |
devicePath | String : the path on the device where to put the dump. This must be a location where permissions allow it. |
| Возвраты | |
|---|---|
File | the File containing the report. Null if something failed. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
enableAdbRoot
public 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.
| Возвраты | |
|---|---|
boolean | true if successful. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
enableNetworkMonitor
public boolean enableNetworkMonitor ()
Enables network monitoring on device.
| Возвраты | |
|---|---|
boolean | true if monitoring is enabled successfully. false if it failed. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbCommand
public String executeAdbCommand (long timeout,
String... cmdArgs)Helper method which executes a adb command as a system command with a specified timeout.
executeShellCommand(String) should be used instead wherever possible, as that method provides better failure detection and performance.
| Параметры | |
|---|---|
timeout | long : the time in milliseconds before the device is considered unresponsive, 0L for no timeout |
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
String | the stdout from command. null if command failed to execute. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbCommand
public 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.| Параметры | |
|---|---|
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
String | the stdout from command. null if command failed to execute. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbCommand
public String executeAdbCommand (long timeout,
Map<String, String> envMap,
String... cmdArgs)Helper method which executes a adb command as a system command with a specified timeout.
executeShellCommand(String) should be used instead wherever possible, as that method provides better failure detection and performance.
| Параметры | |
|---|---|
timeout | long : the time in milliseconds before the device is considered unresponsive, 0L for no timeout |
envMap | Map : environment to set for the command |
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
String | the stdout from command. null if command failed to execute. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbV2Command
public CommandResult executeAdbV2Command (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.
| Параметры | |
|---|---|
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbV2Command
public CommandResult executeAdbV2Command (long timeout, String... cmdArgs)
Helper method which executes a adb command as a system command with a specified timeout.
executeShellCommand(String) should be used instead wherever possible, as that method provides better failure detection and performance.
| Параметры | |
|---|---|
timeout | long : the time in milliseconds before the device is considered unresponsive, 0L for no timeout |
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbV2Command
public CommandResult executeAdbV2Command (long timeout, Map<String, String> envMap, String... cmdArgs)
Helper method which executes a adb command as a system command with a specified timeout.
executeShellCommand(String) should be used instead wherever possible, as that method provides better failure detection and performance.
| Параметры | |
|---|---|
timeout | long : the time in milliseconds before the device is considered unresponsive, 0L for no timeout |
envMap | Map : environment to set for the command |
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeAdbV2Command
public CommandResult executeAdbV2Command (long timeout, Map<String, String> envMap, int retryAttempts, String... cmdArgs)
Helper method which executes a adb command as a system command with a specified timeout.
executeShellCommand(String) should be used instead wherever possible, as that method provides better failure detection and performance.
| Параметры | |
|---|---|
timeout | long : the time in milliseconds before the device is considered unresponsive, 0L for no timeout |
envMap | Map : environment to set for the command |
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. |
cmdArgs | String : the adb command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeFastbootCommand
public 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.
| Параметры | |
|---|---|
cmdArgs | String : the fastboot command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
executeFastbootCommand
public 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.| Параметры | |
|---|---|
timeout | long : the time in milliseconds before the command expire |
cmdArgs | String : the fastboot command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
executeLongFastbootCommand
public CommandResult executeLongFastbootCommand (String... cmdArgs)
Helper method which executes a long running fastboot command as a system command.
Identical toexecuteFastbootCommand(String...) except uses a longer timeout.| Параметры | |
|---|---|
cmdArgs | String : the fastboot command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
executeLongFastbootCommand
public CommandResult executeLongFastbootCommand (Map<String, String> envVarMap, String... cmdArgs)
Helper method which executes a long running fastboot command as a system command with system environment variables.
Identical to executeFastbootCommand(String...) except uses a longer timeout.
| Параметры | |
|---|---|
envVarMap | Map : the system environment variables that the fastboot command run with |
cmdArgs | String : the fastboot command and arguments to run |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
executeShellCommand
public String executeShellCommand (String command)
Helper method which executes a adb shell command and returns output as a String .
| Параметры | |
|---|---|
command | String : the adb shell command to run |
| Возвраты | |
|---|---|
String | the shell output |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellCommand
public void executeShellCommand (String command,
IShellOutputReceiver receiver,
long maxTimeToOutputShellResponse,
TimeUnit timeUnit,
int retryAttempts)Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
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. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellCommand
public void executeShellCommand (String command,
IShellOutputReceiver receiver,
long maxTimeoutForCommand,
long maxTimeToOutputShellResponse,
TimeUnit timeUnit,
int retryAttempts)Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
command | String : the adb shell command to run |
receiver | IShellOutputReceiver : the IShellOutputReceiver to direct shell output to. |
maxTimeoutForCommand | long : the maximum timeout for the command to complete; unit as specified in timeUnit |
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. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellCommand
public void executeShellCommand (String command,
IShellOutputReceiver receiver)Executes the given adb shell command, retrying multiple times if command fails.
A simpler form ofexecuteShellCommand(String,IShellOutputReceiver,long,TimeUnit,int) with default values.| Параметры | |
|---|---|
command | String : the adb shell command to run |
receiver | IShellOutputReceiver : the IShellOutputReceiver to direct shell output to. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd)
Helper method which executes a adb shell command and returns the results as a CommandResult properly populated with the command status output, stdout and stderr.
| Параметры | |
|---|---|
cmd | String : The command that should be run. |
| Возвраты | |
|---|---|
CommandResult | The result in CommandResult . |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)
Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
cmd | String : the adb shell command to run |
pipeAsInput | File : A File that will be piped as input to the command, or null. |
pipeToOutput | OutputStream : OutputStream where the std output will be redirected, or null. |
maxTimeoutForCommand | long : the maximum timeout for the command to complete; 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. |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit)
Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
cmd | String : the adb shell command to run |
maxTimeoutForCommand | long : the maximum timeout for the command to complete; unit as specified in timeUnit |
timeUnit | TimeUnit : unit for maxTimeToOutputShellResponse |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, File pipeAsInput)
Helper method which executes an adb shell command and returns the results as a CommandResult properly populated with the command status output, stdout and stderr.
| Параметры | |
|---|---|
cmd | String : The command that should be run. |
pipeAsInput | File : A File that will be piped as input to the command, or null. |
| Возвраты | |
|---|---|
CommandResult | The result in CommandResult . |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)
Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
cmd | String : the adb shell command to run |
maxTimeoutForCommand | long : the maximum timeout for the command to complete; 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. |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, OutputStream pipeToOutput)
Helper method which executes an adb shell command and returns the results as a CommandResult properly populated with the command status output and stderr. stdout is directed to the specified stream.
| Параметры | |
|---|---|
cmd | String : The command that should be run. |
pipeToOutput | OutputStream : OutputStream where the std output will be redirected, or null. |
| Возвраты | |
|---|---|
CommandResult | The result in CommandResult . |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)
Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
cmd | String : the adb shell command to run |
pipeAsInput | File : A File that will be piped as input to the command, or null. |
pipeToOutput | OutputStream : OutputStream where the std output will be redirected, or null. |
pipeToError | OutputStream : OutputStream where the std error will be redirected, or null. |
maxTimeoutForCommand | long : the maximum timeout for the command to complete; 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. |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, long maxTimeoutForCommand, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)
Executes a adb shell command, with more parameters to control command behavior.
| Параметры | |
|---|---|
cmd | String : the adb shell command to run |
pipeAsInput | File : A File that will be piped as input to the command, or null. |
pipeToOutput | OutputStream : OutputStream where the std output will be redirected, or null. |
pipeToError | OutputStream : OutputStream where the std error will be redirected, or null. |
maxTimeoutForCommand | long : the maximum timeout for the command to complete; unit as specified in timeUnit |
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. |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
executeShellV2Command
public CommandResult executeShellV2Command (String cmd, IShellOutputReceiver receiver)
Helper method which executes a adb shell command and returns the results as a CommandResult properly populated with the command status output, stdout and stderr.
| Параметры | |
|---|---|
cmd | String : The command that should be run. |
receiver | IShellOutputReceiver : the IShellOutputReceiver to direct shell output to. |
| Возвраты | |
|---|---|
CommandResult | The result in CommandResult . |
| Броски | |
|---|---|
DeviceNotAvailableException | |
fastbootOemRamdumpNow
public CommandResult fastbootOemRamdumpNow ()
Helper method which triggers ramdump from a fastboot mode.
This method executes the "oem ramdump now" command. UnlikeERROR(/#executeFastbootCommand()) , it does not attempt retries or device recovery if the command fails or the status is invalid, as a device crash is the intended outcome. Expected to be used when device is already in fastboot mode.| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command |
fastbootWipePartition
public CommandResult fastbootWipePartition (String partition)
Helper method which wipes a partition for the device.
IfgetUseFastbootErase() 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.| Параметры | |
|---|---|
partition | String : the partition to wipe |
| Возвраты | |
|---|---|
CommandResult | the CommandResult containing output of command |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getActiveApexes
public Set<ITestDevice.ApexInfo> getActiveApexes ()
Fetch the information about APEXes activated on the device.
| Возвраты | |
|---|---|
Set< ITestDevice.ApexInfo > | Set of ApexInfo currently activated on the device |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getAdbPath
public String getAdbPath ()
Returns the path of the adb binary being used.
| Возвраты | |
|---|---|
String | |
getAllSettings
public Map<String, String> getAllSettings (String namespace)
Return key value pairs of requested namespace.
| Параметры | |
|---|---|
namespace | String : must be one of {"system", "secure", "global"} |
| Возвраты | |
|---|---|
Map<String, String> | the map of key value pairs. Null if namespace is not supported. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getAllocationState
public DeviceAllocationState getAllocationState ()
Return the current allocation state of device
| Возвраты | |
|---|---|
DeviceAllocationState | |
getAndroidId
public String getAndroidId (int userId)
Find and return the android-id associated to a userId, null if not found.
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
String | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getAndroidIds
public 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.
| Возвраты | |
|---|---|
Map<Integer, String> | Map of android ids found matching user ids. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getApiLevel
public int getApiLevel ()
Get the device API Level. Defaults to UNKNOWN_API_LEVEL .
| Возвраты | |
|---|---|
int | an integer indicating the API Level of device |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getApiLevelFull
public int getApiLevelFull ()
Similar to getApiLevel() , but returns the full version.
| Возвраты | |
|---|---|
int | an integer indicating the full API Level of device |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getAppPackageInfo
public PackageInfo getAppPackageInfo (String packageName)
Fetch information about a package installed on device.
| Параметры | |
|---|---|
packageName | String |
| Возвраты | |
|---|---|
PackageInfo | the PackageInfo or null if information could not be retrieved |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getAppPackageInfos
public List<PackageInfo> getAppPackageInfos ()
Fetch information of packages installed on the device.
| Возвраты | |
|---|---|
List< PackageInfo > | List of PackageInfo s installed on the device. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBasebandVersion
public 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 .
| Возвраты | |
|---|---|
String | the String baseband version or null if it cannot be determined (device has no radio or version string cannot be read) |
| Броски | |
|---|---|
DeviceNotAvailableException | |
получить батарею
public Integer getBattery ()
Returns the current battery level of a device or Null if battery level unavailable.
| Возвраты | |
|---|---|
Integer | |
getBooleanProperty
public boolean getBooleanProperty (String name,
boolean defaultValue)Returns boolean value of the given property.
| Параметры | |
|---|---|
name | String : the property name |
defaultValue | boolean : default value to return if property is empty or doesn't exist. |
| Возвраты | |
|---|---|
boolean | true if the property has value "1" , "y" , "yes" , "on" , or "true" , false if the property has value of "0" , "n" , "no" , "off" , "false" , or defaultValue otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBootHistory
public Map<Long, String> getBootHistory ()
Helper method collects the boot history map with boot time and boot reason.
| Возвраты | |
|---|---|
Map<Long, String> | Map of boot time (UTC time in second since Epoch) and boot reason |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBootHistorySince
public Map<Long, String> getBootHistorySince (long utcEpochTime,
TimeUnit timeUnit)Helper method collects the boot history map with boot time and boot reason since the given time since epoch from device and the time unit specified. The current device utcEpochTime in Millisecond can be obtained by method getDeviceDate() .
| Параметры | |
|---|---|
utcEpochTime | long : the device time since Epoch. |
timeUnit | TimeUnit : the time unit TimeUnit . |
| Возвраты | |
|---|---|
Map<Long, String> | Map of boot time (UTC time in second since Epoch) and boot reason |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBootloaderVersion
public 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)| Возвраты | |
|---|---|
String | the String bootloader version or null if it cannot be found |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
getBugreport
public 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).
| Возвраты | |
|---|---|
InputStreamSource | An InputStreamSource which will produce the bugreport contents on demand. In case of failure, the InputStreamSource will produce an empty InputStream . |
getBugreportz
public 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
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the zip file containing the bugreportz, return null in case of failure. |
getBuildAlias
public 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
| Возвраты | |
|---|---|
String | the build alias or fall back to build id if it could not be retrieved |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBuildFlavor
public String getBuildFlavor ()
Retrieve the build flavor for the device.
| Возвраты | |
|---|---|
String | the build flavor or null if it could not be retrieved |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBuildId
public String getBuildId ()
Retrieve the build the device is currently running.
| Возвраты | |
|---|---|
String | the build id or IBuildInfo.UNKNOWN_BUILD_ID if it could not be retrieved |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getBuildSigningKeys
public 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 | The signing key if found, null otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getCachedDeviceDescriptor
public DeviceDescriptor getCachedDeviceDescriptor ()
Returns a cached DeviceDescriptor if the device is allocated, otherwise returns the current DeviceDescriptor .
| Возвраты | |
|---|---|
DeviceDescriptor | |
getCachedDeviceDescriptor
public DeviceDescriptor getCachedDeviceDescriptor (boolean shortDescriptor)
Returns a cached DeviceDescriptor if the device is allocated, otherwise returns the current DeviceDescriptor .
| Параметры | |
|---|---|
shortDescriptor | boolean : Whether or not to limit descriptor to bare minimum info |
| Возвраты | |
|---|---|
DeviceDescriptor | |
getChildren
public String[] getChildren (String path)
Alternative to using IFileEntry that sometimes won't work because of permissions.
| Параметры | |
|---|---|
path | String : is the path on the device where to do the search |
| Возвраты | |
|---|---|
String[] | Array of string containing all the file in a path on the device. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getConnection
public AbstractConnection getConnection ()
The current connection associated with the device.
| Возвраты | |
|---|---|
AbstractConnection | |
getContentProvider
public ContentProviderHandler getContentProvider (int userId)
Returns the ContentProviderHandler or null if not available.
Content provider can be reused if it was constructed before with the same userId .
| Параметры | |
|---|---|
userId | int : the user id to initialize the content provider with. |
| Возвраты | |
|---|---|
ContentProviderHandler | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getCurrentFoldableState
public DeviceFoldableState getCurrentFoldableState ()
Returns the current foldable state of the device or null if some issues occurred.
| Возвраты | |
|---|---|
DeviceFoldableState | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getCurrentUser
public int getCurrentUser ()
Return the id of the current running user. In case of error, return -10000.
| Возвраты | |
|---|---|
int | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getDeviceClass
public String getDeviceClass ()
Get the device class.
| Возвраты | |
|---|---|
String | the String device class. |
getDeviceDate
public long getDeviceDate ()
Return the date of the device in millisecond since epoch.
| Возвраты | |
|---|---|
long | the date of the device in epoch format. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getDeviceDescriptor
public DeviceDescriptor getDeviceDescriptor ()
Return a DeviceDescriptor from the device information to get info on it without passing the actual device object.
| Возвраты | |
|---|---|
DeviceDescriptor | |
getDeviceDescriptor
public DeviceDescriptor getDeviceDescriptor (boolean shortDescriptor)
Return a DeviceDescriptor from the device information to get info on it without passing the actual device object.
| Параметры | |
|---|---|
shortDescriptor | boolean : Whether or not to limit descriptor to bare minimum info |
| Возвраты | |
|---|---|
DeviceDescriptor | |
getDeviceState
public TestDeviceState getDeviceState ()
Get the device's state.
| Возвраты | |
|---|---|
TestDeviceState | |
getDeviceTimeOffset
public long getDeviceTimeOffset (Date date)
Helper to get the time difference between the device and a given Date . Use Epoch time internally.
| Параметры | |
|---|---|
date | Date |
| Возвраты | |
|---|---|
long | the difference in milliseconds |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getEmulatorOutput
public InputStreamSource getEmulatorOutput ()
Get the stream of emulator stdout and stderr
| Возвраты | |
|---|---|
InputStreamSource | emulator output |
getEmulatorProcess
public Process getEmulatorProcess ()
Return the Process corresponding to this emulator.
| Возвраты | |
|---|---|
Process | the Process or null |
getExecuteShellCommandLog
public final File getExecuteShellCommandLog ()
The log that contains all the executeShellCommand(String) logs.
| Возвраты | |
|---|---|
File | |
getExternalStoreFreeSpace
public long getExternalStoreFreeSpace ()
Helper method to determine amount of free space on device external storage.
| Возвраты | |
|---|---|
long | the amount of free space in KB |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getFastbootPath
public String getFastbootPath ()
Returns the path of the fastboot binary being used. Still requires isFastbootEnabled() to be true, to have fastboot functions enabled.
| Возвраты | |
|---|---|
String | |
getFastbootProductType
public 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 genericgetProductType() method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.| Возвраты | |
|---|---|
String | the String product type name or null if it cannot be determined |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
getFastbootProductVariant
public 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 genericgetProductType() method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.| Возвраты | |
|---|---|
String | the String product type name or null if it cannot be determined |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
getFastbootSerialNumber
public String getFastbootSerialNumber ()
Returns the fastboot mode serial number.
| Возвраты | |
|---|---|
String | |
getFastbootVariable
public String getFastbootVariable (String variableName)
Retrieve the given fastboot variable value from the device.
| Параметры | |
|---|---|
variableName | String : the variable name |
| Возвраты | |
|---|---|
String | the property value or null if it does not exist |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
getFastbootVersion
public String getFastbootVersion ()
Returns the version string of the fastboot binary being used. Or null if something goes wrong.
| Возвраты | |
|---|---|
String | |
getFileEntry
public IFileEntry getFileEntry (String path)
Retrieve a reference to a remote file on device.
| Параметры | |
|---|---|
path | String : the file path to retrieve. Can be an absolute path or path relative to '/'. (ie both "/system" and "system" syntax is supported) |
| Возвраты | |
|---|---|
IFileEntry | the IFileEntry or null if file at given path cannot be found |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getFileEntry
public IFileEntry getFileEntry (FileListingService.FileEntry entry)
Unofficial helper to get a FileEntry from a non-root path. FIXME: Refactor the FileEntry system to have it available from any path. (even non root).
| Параметры | |
|---|---|
entry | FileListingService.FileEntry : a FileEntry not necessarily root as Ddmlib requires. |
| Возвраты | |
|---|---|
IFileEntry | a FileEntryWrapper representing the FileEntry. |
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
getFoldableStates
public Set<DeviceFoldableState> getFoldableStates ()
Returns the list of foldable states on the device. Can be obtained with "cmd device_state print-states".
| Возвраты | |
|---|---|
Set< DeviceFoldableState > | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getIDevice
public IDevice getIDevice ()
Returns a reference to the associated ddmlib IDevice .
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.| Возвраты | |
|---|---|
IDevice | the IDevice |
getInstalledPackageNames
public Set<String> getInstalledPackageNames ()
Fetch the application package names present on the device.
| Возвраты | |
|---|---|
Set<String> | Set of String package names currently installed on the device. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getIntProperty
public long getIntProperty (String name,
long defaultValue)Returns integer value of the given property from the device.
| Параметры | |
|---|---|
name | String : the property name |
defaultValue | long : default value to return if property is empty or doesn't exist. |
| Возвраты | |
|---|---|
long | the property value or defaultValue if the property is empty, doesn't exist, or doesn't have an integer value. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
получить IP-адрес
public String getIpAddress ()
Gets the device's IP address.
| Возвраты | |
|---|---|
String | the device's IP address, or null if device has no IP address |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getKeyguardState
public KeyguardControllerState getKeyguardState ()
Return an object to get the current state of the keyguard or null if not supported.
| Возвраты | |
|---|---|
KeyguardControllerState | a KeyguardControllerState containing a snapshot of the state of the keyguard and returns Null if the Keyguard query is not supported. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getLastExpectedRebootTimeMillis
public long getLastExpectedRebootTimeMillis ()
Returns the last time Tradefed APIs triggered a reboot in milliseconds since EPOCH as returned by System.currentTimeMillis() .
| Возвраты | |
|---|---|
long | |
getLaunchApiLevel
public int getLaunchApiLevel ()
Get the device's first launched API Level. Defaults to UNKNOWN_API_LEVEL .
| Возвраты | |
|---|---|
int | an integer indicating the first launched API Level of device |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getLogcat
public InputStreamSource getLogcat ()
Grabs a snapshot stream of the logcat data.
Работает в двух режимах:
TestDeviceOptions.getMaxLogcatDataSize() bytes of the current contents of the background logcat capture| Возвраты | |
|---|---|
InputStreamSource | |
getLogcat
public 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.
| Параметры | |
|---|---|
maxBytes | int : the maximum amount of data to return. Should be an amount that can comfortably fit in memory |
| Возвраты | |
|---|---|
InputStreamSource | |
getLogcatDump
public 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.
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the logcat data. An empty stream is returned if fail to capture logcat data. |
getLogcatSince
public 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() .
| Параметры | |
|---|---|
date | long : in millisecond since epoch format of when to start the snapshot until present. (can be be obtained using 'date +%s') |
| Возвраты | |
|---|---|
InputStreamSource | |
получитьMac-адрес
public String getMacAddress ()
Returns the MAC address of the device, null if it fails to query from the device.
| Возвраты | |
|---|---|
String | |
getMainUserId
public Integer getMainUserId ()
Returns the main user id.
| Возвраты | |
|---|---|
Integer | the userId of the main user if there is one, and null if there is no main user. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getMainlineModuleInfo
public Set<String> getMainlineModuleInfo ()
Get the information about the mainline modules installed on the device.
| Возвраты | |
|---|---|
Set<String> | Set of String mainline modules currently installed on the device. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getMaxNumberOfRunningUsersSupported
public int getMaxNumberOfRunningUsersSupported ()
Get the maximum number of supported simultaneously running users. Defaults to 0.
| Возвраты | |
|---|---|
int | an integer indicating the number of simultaneously running users |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getMaxNumberOfUsersSupported
public int getMaxNumberOfUsersSupported (String userType)
Get the maximum number of supported users of the given user type. Defaults to 0.
| Параметры | |
|---|---|
userType | String : the type of user, as defined in UserManager, such as "android.os.usertype.full.SECONDARY". |
| Возвраты | |
|---|---|
int | an integer indicating the number of supported users of the given user type |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getMaxNumberOfUsersSupported
public int getMaxNumberOfUsersSupported ()
Get the maximum number of supported switchable users, not including Guests. After api version 36, does not include non-switchable users (like profiles). Defaults to 0.
| Возвраты | |
|---|---|
int | an integer indicating the number of supported switchable users |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getMicrodroidProcess
public Process getMicrodroidProcess ()
| Возвраты | |
|---|---|
Process | Returns the Process of the Microdroid VM. If TestDevice is not a Microdroid, returns null. |
getMonitor
public IDeviceStateMonitor getMonitor ()
Return the IDeviceStateMonitor associated with device.
| Возвраты | |
|---|---|
IDeviceStateMonitor | |
getMountPoint
public String getMountPoint (String mountName)
Returns a mount point.
Queries the device directly if the cached info inIDevice is not available. TODO: move this behavior to IDevice.getMountPoint(String)| Параметры | |
|---|---|
mountName | String : the name of the mount point |
| Возвраты | |
|---|---|
String | the mount point or null |
getMountPointInfo
public ITestDevice.MountPointInfo getMountPointInfo (String mountpoint)
Returns a 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.
| Параметры | |
|---|---|
mountpoint | String |
| Возвраты | |
|---|---|
ITestDevice.MountPointInfo | A List of MountPointInfo containing the information in "/proc/mounts" |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getMountPointInfo
public List<ITestDevice.MountPointInfo> getMountPointInfo ()
Returns a parsed version of the information in /proc/mounts on the device
| Возвраты | |
|---|---|
List< ITestDevice.MountPointInfo > | A List of MountPointInfo containing the information in "/proc/mounts" |
| Броски | |
|---|---|
DeviceNotAvailableException | |
получить параметры
public TestDeviceOptions getOptions ()
Fetch the test options for the device.
| Возвраты | |
|---|---|
TestDeviceOptions | TestDeviceOptions related to the device under test. |
getPartitionFreeSpace
public long getPartitionFreeSpace (String partition)
Helper method to determine amount of free space on device partition.
| Параметры | |
|---|---|
partition | String |
| Возвраты | |
|---|---|
long | the amount of free space in KB |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getPrimaryUserId
public Integer getPrimaryUserId ()
Returns the primary user id.
| Возвраты | |
|---|---|
Integer | the userId of the primary user if there is one, and null if there is no primary user. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getProcessByName
public ProcessInfo getProcessByName (String processName)
Helper method runs the "pidof" and "stat" command and returns ProcessInfo object with PID and process start time of the given process.
| Параметры | |
|---|---|
processName | String : the proces name String. |
| Возвраты | |
|---|---|
ProcessInfo | ProcessInfo of given processName |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getProcessPid
public String getProcessPid (String process)
Returns the pid of the service or null if something went wrong.
| Параметры | |
|---|---|
process | String : The proces name String. |
| Возвраты | |
|---|---|
String | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getProductType
public 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.| Возвраты | |
|---|---|
String | the String product type name. Will not be null |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getProductVariant
public 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.| Возвраты | |
|---|---|
String | the String product variant name or null if it cannot be determined |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getProperty
public String getProperty (String name)
Retrieve the given property value from the device.
| Параметры | |
|---|---|
name | String : the property name |
| Возвраты | |
|---|---|
String | the property value or null if it does not exist |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getRecoveryMode
public ITestDevice.RecoveryMode getRecoveryMode ()
Get the current recovery mode used for the device.
| Возвраты | |
|---|---|
ITestDevice.RecoveryMode | the current recovery mode used for the device. |
getRemainingCreatableUserCount
public int getRemainingCreatableUserCount (String userType)
Returns how many users of the given user type can be created on this device.
| Параметры | |
|---|---|
userType | String : the type of user, as defined in UserManager, such as "android.os.usertype.full.SECONDARY". |
| Возвраты | |
|---|---|
int | how many users of the given user type can be added |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getScreenshot
public InputStreamSource getScreenshot (Long displayId, String format, boolean rescale)
Grabs a screenshot from the device given display id with supported format. Allow rescale to support smaller size
| Параметры | |
|---|---|
displayId | Long : the display id of the screen to get screenshot from. |
format | String : supported PNG, JPEG |
rescale | boolean : if screenshot should be rescaled to reduce the size of resulting image |
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getScreenshot
public InputStreamSource getScreenshot (String format)
Grabs a screenshot from the device. Recommended to use getScreenshot(format) instead with JPEG encoding for smaller size
| Параметры | |
|---|---|
format | String : supported PNG, JPEG |
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getScreenshot
public InputStreamSource getScreenshot (long displayId)
Grabs a screenshot from the device given display id. Format is PNG.
TODO: extend the implementations above to support 'format' and 'rescale'
| Параметры | |
|---|---|
displayId | long : the display id of the screen to get screenshot from. |
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getScreenshot
public InputStreamSource getScreenshot (String format, boolean rescale)
Grabs a screenshot from the device. Recommended to use getScreenshot(String) instead with JPEG encoding for smaller size.
| Параметры | |
|---|---|
format | String : supported PNG, JPEG |
rescale | boolean : if screenshot should be rescaled to reduce the size of resulting image |
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getScreenshot
public InputStreamSource getScreenshot ()
Grabs a screenshot from the device.
| Возвраты | |
|---|---|
InputStreamSource | a InputStreamSource of the screenshot in png format, or null if the screenshot was not successful. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getSerialNumber
public String getSerialNumber ()
Convenience method to get serial number of this device.
| Возвраты | |
|---|---|
String | the String serial number |
getSetting
public String getSetting (int userId,
String namespace,
String key)Return the value of the requested setting. namespace must be one of: {"system", "secure", "global"}
| Параметры | |
|---|---|
userId | int |
namespace | String |
key | String |
| Возвраты | |
|---|---|
String | the value associated with the namespace:key of a user. Null if not found. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getSetting
public String getSetting (String namespace,
String key) See getSetting(int,String,String) and performed on system user.
| Параметры | |
|---|---|
namespace | String |
key | String |
| Возвраты | |
|---|---|
String | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getSimOperator
public String getSimOperator ()
Return the SIM card operator or null if not available or if device is not available.
| Возвраты | |
|---|---|
String | |
getSimState
public String getSimState ()
Return the SIM card state or null if not available or device is not available.
| Возвраты | |
|---|---|
String | |
getTombstones
public List<File> getTombstones ()
Fetch and return the list of tombstones from the devices. Requires root.
method is best-effort so if one tombstone fails to be pulled for any reason it will be missing from the list. Only a DeviceNotAvailableException will terminate the method early.
| Возвраты | |
|---|---|
List<File> | A list of tombstone files, empty if no tombstone. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getTotalMemory
public long getTotalMemory ()
Returns total physical memory size in bytes or -1 in case of internal error
| Возвраты | |
|---|---|
long | |
getTrackingSerial
public String getTrackingSerial ()
For device management purpose get the serial used to track the device.
| Возвраты | |
|---|---|
String | |
getUninstallablePackageNames
public Set<String> getUninstallablePackageNames ()
Fetch the application package names that can be uninstalled. This is presently defined as non-system packages, and updated system packages.
| Возвраты | |
|---|---|
Set<String> | Set of uninstallable String package names currently installed on the device. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getUseFastbootErase
public boolean getUseFastbootErase ()
Get whether to use fastboot erase or fastboot format to wipe a partition on the device.
| Возвраты | |
|---|---|
boolean | true if fastboot erase will be used or false if fastboot format will be used. |
getUserFlags
public 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.
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
int | the flags associated with the userId provided if found, -10000 in any other cases. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getUserInfos
public Map<Integer, UserInfo> getUserInfos ()
Gets the Map of useId to UserInfo on the device. Will throw DeviceRuntimeException if output from device is not as expected.
| Возвраты | |
|---|---|
Map<Integer, UserInfo > | the list of UserInfo objects. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getUserSerialNumber
public int getUserSerialNumber (int userId)
Return the serial number associated to the userId if found, -10000 in any other cases.
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
int | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
getUserVisibleOnDisplay
public int getUserVisibleOnDisplay (int displayId)
Gets the user id of the visible user on the given display.
| Параметры | |
|---|---|
displayId | int : the id of the display. |
| Возвраты | |
|---|---|
int | the user id of the visible user on the given display. It does not differentiate a visible background user from the current foreground user as both types are visible. To differentiate, further compare with the result of getCurrentUser(). |
| Броски | |
|---|---|
DeviceNotAvailableException | |
handleAllocationEvent
public 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.
| Параметры | |
|---|---|
event | DeviceEvent |
| Возвраты | |
|---|---|
IManagedTestDevice.DeviceEventResponse | |
hasFeature
public boolean hasFeature (String feature)
Check if a feature is available on a device.
| Параметры | |
|---|---|
feature | String : which format should be "feature: |
| Возвраты | |
|---|---|
boolean | True if feature is found, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
initializeConnection
public void initializeConnection (IBuildInfo info, MultiMap<String, String> attributes)
Initialize the connection to the device. This is called by preInvocationSetup but in rare cases might need to be called separately when creating the connection during device setup.
| Параметры | |
|---|---|
info | IBuildInfo |
attributes | MultiMap |
| Броски | |
|---|---|
DeviceNotAvailableException | |
TargetSetupError | |
installPackage
public 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.
| Параметры | |
|---|---|
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 -h' for available options. |
| Возвраты | |
|---|---|
String | a String with an error code, or null if success. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
installPackage
public String installPackage (File packageFile,
boolean reinstall,
String... extraArgs)Install an Android package on device.
| Параметры | |
|---|---|
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 -h' for available options. |
| Возвраты | |
|---|---|
String | a String with an error code, or null if success. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
installPackageForUser
public 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.
| Параметры | |
|---|---|
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 -h' for available options. |
| Возвраты | |
|---|---|
String | a String with an error code, or null if success. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
installPackageForUser
public String installPackageForUser (File packageFile,
boolean reinstall,
int userId,
String... extraArgs)Install an Android package on device for a given user.
| Параметры | |
|---|---|
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 -h' for available options. |
| Возвраты | |
|---|---|
String | a String with an error code, or null if success. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
installPackageWithIncrementalMode
public boolean installPackageWithIncrementalMode (File[] apkFiles,
String[] extraArgs,
String userId)Installs apks with incremental mode.
| Параметры | |
|---|---|
apkFiles | File : the apk files to install. |
extraArgs | String |
userId | String |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
invalidatePropertyCache
public void invalidatePropertyCache ()
isAdbTcp
public boolean isAdbTcp ()
| Возвраты | |
|---|---|
boolean | |
isAppEnumerationSupported
public boolean isAppEnumerationSupported ()
Check whether platform on device supports app enumeration
| Возвраты | |
|---|---|
boolean | True if app enumeration is supported, false otherwise |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isBypassLowTargetSdkBlockSupported
public boolean isBypassLowTargetSdkBlockSupported ()
Check whether platform on device supports bypassing low target sdk block on app installs
| Возвраты | |
|---|---|
boolean | True if bypass low target sdk block is supported, false otherwise |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isDebugfsMounted
public boolean isDebugfsMounted ()
Check if debugfs is mounted.
| Возвраты | |
|---|---|
boolean | true if debugfs is mounted |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isDeviceEncrypted
public boolean isDeviceEncrypted ()
Returns if the device is encrypted.
| Возвраты | |
|---|---|
boolean | true if the device is encrypted. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isDirectory
public boolean isDirectory (String path)
Return True if the path on the device is a directory, false otherwise.
| Параметры | |
|---|---|
path | String |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isEnableAdbRoot
public boolean isEnableAdbRoot ()
| Возвраты | |
|---|---|
boolean | true if adb root should be enabled on device |
isEncryptionSupported
public boolean isEncryptionSupported ()
Returns if encryption is supported on the device.
| Возвраты | |
|---|---|
boolean | true if the device supports encryption. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isExecutable
public boolean isExecutable (String fullPath)
Returns True if the file path on the device is an executable file, false otherwise.
| Параметры | |
|---|---|
fullPath | String |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isFastbootEnabled
public boolean isFastbootEnabled ()
Return if fastboot is available for the device.
| Возвраты | |
|---|---|
boolean | |
isHeadless
public boolean isHeadless ()
Return true if the device is headless (no screen), false otherwise.
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isHeadlessSystemUserMode
public boolean isHeadlessSystemUserMode ()
Returns whether the device uses headless system user mode.
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isMainUserPermanentAdmin
public boolean isMainUserPermanentAdmin ()
Returns whether the main user is a permanent admin and can't be deleted or downgraded to non-admin status.
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isMultiUserSupported
public boolean isMultiUserSupported ()
Returns whether this device supports multiple switchable users with their own login and customizable space.
Note that, even if false, multiple users might still be possible, as long as no login UI is required; eg, profiles might still be supported, as they do not require a login UI.
This also checks config_enableMultiUserUI. By demand, we are allowed to assume that devices for which this is true are configured to allow adding secondary users via adb.
| Возвраты | |
|---|---|
boolean | whether the device supports multiple switchable users. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isPackageInstalled
public boolean isPackageInstalled (String packageName,
String userId)Query the device for a given package name and given user id to check if it's currently installed or not for that user.
| Параметры | |
|---|---|
packageName | String : the package we are checking if it's installed. |
userId | String : The user id we are checking the package is installed for. If null, primary user zero will be used. |
| Возвраты | |
|---|---|
boolean | True if the package is reported as installed. False otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isPackageInstalled
public boolean isPackageInstalled (String packageName)
Query the device for a given package name to check if it's currently installed or not.
| Параметры | |
|---|---|
packageName | String |
| Возвраты | |
|---|---|
boolean | True if the package is reported as installed. False otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isRuntimePermissionSupported
public boolean isRuntimePermissionSupported ()
Check whether platform on device supports runtime permission granting
| Возвраты | |
|---|---|
boolean | True if runtime permission are supported, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isShellV2Support
public boolean isShellV2Support ()
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isStateBootloaderOrFastbootd
public boolean isStateBootloaderOrFastbootd ()
Returns true if device is in TestDeviceState.FASTBOOT or TestDeviceState.FASTBOOTD .
| Возвраты | |
|---|---|
boolean | |
isUserRunning
public boolean isUserRunning (int userId)
Check if a given user is running.
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
boolean | True if the user is running, false in every other cases. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isUserSecondary
public boolean isUserSecondary (int userId)
Return whether the specified user is a secondary user according to it's flags.
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
boolean | true if the user is secondary, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isUserVisible
public boolean isUserVisible (int userId)
Checks if the given user is visible.
A "visible" user is a user that is interacting with the "human" user and hence is able to launch launch activities (typically in the default display).
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isUserVisibleOnDisplay
public boolean isUserVisibleOnDisplay (int userId,
int displayId)Checks if the given user is visible in the given display.
A "visible" user is a user that is interacting with the "human" user and hence is able to launch launch activities in that display.
| Параметры | |
|---|---|
userId | int |
displayId | int |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isVisibleBackgroundUsersOnDefaultDisplaySupported
public boolean isVisibleBackgroundUsersOnDefaultDisplaySupported ()
Returns whether the device allow users to be started visible in the background in the ERROR(/java.android.view.Display#DEFAULT_DISPLAY) .
If it does, you could call startVisibleBackgroundUser(int, int, boolean) , passing a display returned by listDisplayIdsForStartingVisibleBackgroundUsers() (which should include ERROR(/java.android.view.Display#DEFAULT_DISPLAY) ).
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isVisibleBackgroundUsersSupported
public boolean isVisibleBackgroundUsersSupported ()
Returns whether the device allow users to be started visible in the background.
If it does, you could call startVisibleBackgroundUser(int, int, boolean) , passing a display returned by listDisplayIdsForStartingVisibleBackgroundUsers() .
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
isWifiEnabled
public 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, eg mobile data tests.| Возвраты | |
|---|---|
boolean | true if wifi is enabled. false if disabled |
| Броски | |
|---|---|
DeviceNotAvailableException | |
listDisplayIds
public Set<Long> listDisplayIds ()
Collect the list of available displays id on the device as reported by "dumpsys SurfaceFlinger".
| Возвраты | |
|---|---|
Set<Long> | The list of displays. Default always returns the default display 0. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
listDisplayIdsForStartingVisibleBackgroundUsers
public Set<Integer> listDisplayIdsForStartingVisibleBackgroundUsers ()
Gets the list of displays that can be used to start a user visible in the background .
| Возвраты | |
|---|---|
Set<Integer> | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
listUsers
public ArrayList<Integer> listUsers ()
Gets the list of users on the device. Will throw DeviceRuntimeException if output from device is not as expected.
| Возвраты | |
|---|---|
ArrayList<Integer> | the list of user ids. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
logAnrs
public boolean logAnrs (ITestLogger logger)
Collects and log ANRs from the device.
| Параметры | |
|---|---|
logger | ITestLogger : an ITestLogger to log the ANRs. |
| Возвраты | |
|---|---|
boolean | True if the logging was successful, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
logBugreport
public boolean logBugreport (String dataName,
ITestLogger listener)Helper method to take a bugreport and log it to the reporters.
| Параметры | |
|---|---|
dataName | String : name under which the bugreport will be reported. |
listener | ITestLogger : an ITestLogger to log the bugreport. |
| Возвраты | |
|---|---|
boolean | True if the logging was successful, false otherwise. |
logOnDevice
public void logOnDevice (String tag,
Log.LogLevel level,
String format,
Object... args)Log a message in the logcat of the device. This is a safe call that will not throw even if the logging fails.
| Параметры | |
|---|---|
tag | String : The tag under which we log our message in the logcat. |
level | Log.LogLevel : The debug level of the message in the logcat. |
format | String : The message format. |
args | Object : the args to be replaced via String.format(). |
nonBlockingReboot
public void nonBlockingReboot ()
Issues a command to reboot device and returns on command complete and when device is no longer visible to adb.
| Броски | |
|---|---|
DeviceNotAvailableException | |
postAdbRootAction
public 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.
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
postAdbUnrootAction
public 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.
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
postBootSetup
public 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)| Броски | |
|---|---|
DeviceNotAvailableException | |
postInvocationTearDown
public void postInvocationTearDown (Throwable exception)
Extra steps for device specific required clean up that will be executed after the invocation is done.
| Параметры | |
|---|---|
exception | Throwable : if any, the final exception raised by the invocation failure. |
preInvocationSetup
public void preInvocationSetup (IBuildInfo info, MultiMap<String, String> attributes)
Extra steps for device specific required setup that will be executed on the device prior to the invocation flow.
| Параметры | |
|---|---|
info | IBuildInfo : The IBuildInfo of the device. |
attributes | MultiMap : The attributes stored in the invocation context |
| Броски | |
|---|---|
DeviceNotAvailableException | |
TargetSetupError | |
pullDir
public boolean pullDir (String deviceFilePath,
File localDir,
int userId)Recursively pull directory contents from device.
| Параметры | |
|---|---|
deviceFilePath | String : the absolute file path of the remote source |
localDir | File : the local directory to pull files into |
userId | int : the user id to pull from |
| Возвраты | |
|---|---|
boolean | true if file was pulled successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullDir
public boolean pullDir (String deviceFilePath,
File localDir)Recursively pull directory contents from device.
| Параметры | |
|---|---|
deviceFilePath | String : the absolute file path of the remote source |
localDir | File : the local directory to pull files into |
| Возвраты | |
|---|---|
boolean | true if file was pulled successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullDir
public boolean pullDir (String deviceFilePath,
File localDir,
int userId,
long timeout)Recursively pull directory contents from device.
| Параметры | |
|---|---|
deviceFilePath | String : the absolute file path of the remote source |
localDir | File : the local directory to pull files into |
userId | int : the user id to pull from |
timeout | long : the timeout for pulling command |
| Возвраты | |
|---|---|
boolean | true if file was pulled successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFile
public boolean pullFile (String remoteFilePath,
File localFile,
int userId,
long timeout)Retrieves a file off device.
| Параметры | |
|---|---|
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. |
userId | int : The user id to pull from |
timeout | long : pull file command timeout |
| Возвраты | |
|---|---|
boolean | true if file was retrieved successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFile
public boolean pullFile (String remoteFilePath,
File localFile)Retrieves a file off device.
| Параметры | |
|---|---|
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. |
| Возвраты | |
|---|---|
boolean | true if file was retrieved successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFile
public File pullFile (String remoteFilePath,
int userId) Retrieves a file off device, stores it in a local temporary File , and returns that File .
| Параметры | |
|---|---|
remoteFilePath | String : the absolute path to file on device. |
userId | int : The user id to pull from |
| Возвраты | |
|---|---|
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) |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFile
public File pullFile (String remoteFilePath)
Retrieves a file off device, stores it in a local temporary File , and returns that File .
| Параметры | |
|---|---|
remoteFilePath | String : the absolute path to file on device. |
| Возвраты | |
|---|---|
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) |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFile
public boolean pullFile (String remoteFilePath,
File localFile,
int userId)Retrieves a file off device.
| Параметры | |
|---|---|
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. |
userId | int : The user id to pull from |
| Возвраты | |
|---|---|
boolean | true if file was retrieved successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFileContents
public String pullFileContents (String remoteFilePath)
Retrieves a file off device, and returns the contents.
| Параметры | |
|---|---|
remoteFilePath | String : the absolute path to file on device. |
| Возвраты | |
|---|---|
String | A String containing the contents of the device file, or null if the copy failed for any reason (including problems with the host filesystem) |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pullFileFromExternal
public 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 .
| Параметры | |
|---|---|
remoteFilePath | String : the path to file on device, relative to the device's external storage mountpoint |
| Возвраты | |
|---|---|
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) |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushDir
public boolean pushDir (File localFileDir,
String deviceFilePath,
int userId)Recursively push directory contents to device.
| Параметры | |
|---|---|
localFileDir | File : the local directory to push |
deviceFilePath | String : the absolute file path of the remote destination |
userId | int : the user id to push to |
| Возвраты | |
|---|---|
boolean | true if file was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushDir
public boolean pushDir (File localFileDir,
String deviceFilePath,
Set<String> excludedDirectories)Recursively push directory contents to device while excluding some directories that are filtered.
| Параметры | |
|---|---|
localFileDir | File : the local directory to push |
deviceFilePath | String : the absolute file path of the remote destination |
excludedDirectories | Set : Set of excluded directories names that shouldn't be pushed. |
| Возвраты | |
|---|---|
boolean | true if file was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushDir
public boolean pushDir (File localFileDir,
String deviceFilePath)Recursively push directory contents to device.
| Параметры | |
|---|---|
localFileDir | File : the local directory to push |
deviceFilePath | String : the absolute file path of the remote destination |
| Возвраты | |
|---|---|
boolean | true if file was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushFile
public boolean pushFile (File localFile,
String remoteFilePath,
boolean evaluateContentProviderNeeded) Variant of pushFile(File,String) which can optionally consider evaluating the need for the content provider.
| Параметры | |
|---|---|
localFile | File : the local file to push |
remoteFilePath | String : the remote destination absolute file path |
evaluateContentProviderNeeded | boolean : whether to check if we need the content provider |
| Возвраты | |
|---|---|
boolean | true if file was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushFile
public boolean pushFile (File localFile,
String remoteFilePath)Push a file to device. By default using a content provider.
| Параметры | |
|---|---|
localFile | File : the local file to push |
remoteFilePath | String : the remote destination absolute file path |
| Возвраты | |
|---|---|
boolean | true if file was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushFile
public boolean pushFile (File localFile,
String remoteFilePath,
int userId)Push a file to device. By default using a content provider.
| Параметры | |
|---|---|
localFile | File : the local file to push |
remoteFilePath | String : the remote destination absolute file path |
userId | int : the userId to push to |
| Возвраты | |
|---|---|
boolean | true if file was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
pushString
public boolean pushString (String contents,
String remoteFilePath)Push file created from a string to device
| Параметры | |
|---|---|
contents | String : the contents of the file to push |
remoteFilePath | String : the remote destination absolute file path |
| Возвраты | |
|---|---|
boolean | true if string was pushed successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
перезагрузить
public void reboot (String reason)
Reboots the device into adb mode with given reason to be persisted across reboot.
Blocks until device becomes available.
Last reboot reason can be obtained by querying sys.boot.reason property.
| Параметры | |
|---|---|
reason | String : a reason for this reboot, or null if no reason is specified. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
перезагрузить
public String reboot (String command,
String reason) Reboots the device using the given command .
Blocks until device becomes available.
Last reboot reason can be obtained by querying sys.boot.reason property.
| Параметры | |
|---|---|
command | String : command passed to `adb`. Notice that it's passed "as-is", so it's up to the caller to provide the proper quotation if needed (especially if it contains multiple parts separated by space). |
reason | String : a reason for this reboot, or null if no reason is specified. |
| Возвраты | |
|---|---|
String | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
перезагрузить
public void reboot ()
Reboots the device into adb mode.
Blocks until device becomes available.| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootIntoBootloader
public void rebootIntoBootloader ()
Reboots the device into bootloader mode.
Blocks until device is in bootloader mode.| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
rebootIntoFastbootd
public void rebootIntoFastbootd ()
Reboots the device into fastbootd mode.
Blocks until device is in fastbootd mode.
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
rebootIntoRecovery
public void rebootIntoRecovery ()
Reboots the device into adb recovery mode.
Blocks until device enters recovery| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootIntoSideload
public void rebootIntoSideload ()
Reboots the device into adb sideload mode (note that this is a special mode under recovery)
Blocks until device enters sideload mode
| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootIntoSideload
public void rebootIntoSideload (boolean autoReboot)
Reboots the device into adb sideload mode (note that this is a special mode under recovery)
Blocks until device enters sideload mode
| Параметры | |
|---|---|
autoReboot | boolean : whether to automatically reboot the device after sideload |
| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootUntilOnline
public void rebootUntilOnline ()
An alternate to reboot() that only blocks until device is online ie visible to adb.
| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootUntilOnline
public void rebootUntilOnline (String reason)
An alternate to reboot() that only blocks until device is online ie visible to adb.
| Параметры | |
|---|---|
reason | String : a reason for this reboot, or null if no reason is specified. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootUserspace
public void rebootUserspace ()
Reboots only userspace part of device.
Blocks until device becomes available.
WARNING. Userspace reboot is currently under active development, use it on your own risk.
| Броски | |
|---|---|
DeviceNotAvailableException | |
rebootUserspaceUntilOnline
public void rebootUserspaceUntilOnline ()
An alternate to rebootUserspace() ()} that only blocks until device is online ie visible to adb.
| Броски | |
|---|---|
DeviceNotAvailableException | |
recoverDevice
public boolean recoverDevice ()
Attempts to recover device communication.
| Возвраты | |
|---|---|
boolean | True if recovery attempted and successful, returns False if recovery was skipped |
| Броски | |
|---|---|
DeviceNotAvailableException | if device is no longer available |
registerDeviceActionReceiver
public void registerDeviceActionReceiver (IDeviceActionReceiver deviceActionReceiver)
Registers a IDeviceActionReceiver for this device.
All registered IDeviceActionReceiver s will be notified before a device action starts and after the device action ends.
| Параметры | |
|---|---|
deviceActionReceiver | IDeviceActionReceiver : A IDeviceActionReceiver which will be registered. |
remountSystemReadOnly
public void remountSystemReadOnly ()
Make the system partition on the device read-only. May reboot the device.
| Броски | |
|---|---|
DeviceNotAvailableException | |
remountSystemWritable
public void remountSystemWritable ()
Make the system partition on the device writable. May reboot the device.
| Броски | |
|---|---|
DeviceNotAvailableException | |
remountVendorReadOnly
public void remountVendorReadOnly ()
Make the vendor partition on the device read-only. May reboot the device.
| Броски | |
|---|---|
DeviceNotAvailableException | |
remountVendorWritable
public void remountVendorWritable ()
Make the vendor partition on the device writable. May reboot the device.
| Броски | |
|---|---|
DeviceNotAvailableException | |
удалить Администратора
public boolean removeAdmin (String componentName,
int userId) Remove given device admin in given user and return true if it is successful, false otherwise.
| Параметры | |
|---|---|
componentName | String : of device admin to be removed. |
userId | int : of user that the device admin lives in. |
| Возвраты | |
|---|---|
boolean | True if it is successful, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
removeOwners
public void removeOwners ()
Remove all existing device profile owners with the best effort.
| Броски | |
|---|---|
DeviceNotAvailableException | |
removeUser
public boolean removeUser (int userId)
Remove a given user from the device.
| Параметры | |
|---|---|
userId | int : of the user to remove |
| Возвраты | |
|---|---|
boolean | true if we were successful in removing the user, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
resetContentProviderSetup
public void resetContentProviderSetup ()
Reset the flag for content provider setup in order to trigger it again.
runInstrumentationTests
public boolean runInstrumentationTests (IRemoteAndroidTestRunner runner, Collection<ITestLifeCycleReceiver> 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.
| Параметры | |
|---|---|
runner | IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests |
listeners | Collection : the test result listeners |
| Возвраты | |
|---|---|
boolean | true if test command completed. false if it failed to complete due to device communication exception, but recovery succeeded |
| Броски | |
|---|---|
DeviceNotAvailableException | |
runInstrumentationTests
public boolean runInstrumentationTests (IRemoteAndroidTestRunner runner, ITestLifeCycleReceiver... listeners)
Convenience method for performing runInstrumentationTests(IRemoteAndroidTestRunner,Collection) with one or more listeners passed as parameters.
| Параметры | |
|---|---|
runner | IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests |
listeners | ITestLifeCycleReceiver : the test result listener(s) |
| Возвраты | |
|---|---|
boolean | true if test command completed. false if it failed to complete, but recovery succeeded |
| Броски | |
|---|---|
DeviceNotAvailableException | |
runInstrumentationTestsAsUser
public boolean runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, int userId, Collection<ITestLifeCycleReceiver> listeners)
Same as ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner,Collection) but runs the test for the given user.
| Параметры | |
|---|---|
runner | IRemoteAndroidTestRunner |
userId | int |
listeners | Collection |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
runInstrumentationTestsAsUser
public boolean runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, int userId, ITestLifeCycleReceiver... listeners)
Same as ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner,ITestLifeCycleReceiver...) but runs the test for a given user.
| Параметры | |
|---|---|
runner | IRemoteAndroidTestRunner |
userId | int |
listeners | ITestLifeCycleReceiver |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setAdbPath
public void setAdbPath (String adbPath)
Sets the path to the adb binary that should be used.
| Параметры | |
|---|---|
adbPath | String |
setConfiguration
public void setConfiguration (IConfiguration configuration)
Внедряет используемый объект IConfiguration .
| Параметры | |
|---|---|
configuration | IConfiguration |
setConnectionAvdInfo
public final void setConnectionAvdInfo (GceAvdInfo avdInfo)
| Параметры | |
|---|---|
avdInfo | GceAvdInfo |
setDate
public void setDate (Date date)
Sets the date on device
Note: setting date on device requires root
| Параметры | |
|---|---|
date | Date : specify a particular date; will use host date if null |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setDeviceOwner
public boolean setDeviceOwner (String componentName,
int userId)Set a device admin component as device owner in given user.
| Параметры | |
|---|---|
componentName | String : of device admin to be device owner. |
userId | int : of the user that the device owner lives in. |
| Возвраты | |
|---|---|
boolean | True if it is successful, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setDeviceState
public void setDeviceState (TestDeviceState deviceState)
Update the device's state.
| Параметры | |
|---|---|
deviceState | TestDeviceState : the TestDeviceState |
setEmulatorOutputStream
public void setEmulatorOutputStream (SizeLimitedOutputStream output)
For emulator set SizeLimitedOutputStream to log output
| Параметры | |
|---|---|
output | SizeLimitedOutputStream : to log the output |
setEmulatorProcess
public void setEmulatorProcess (Process p)
Sets the Process , when this device is an emulator.
| Параметры | |
|---|---|
p | Process |
setFastbootEnabled
public void setFastbootEnabled (boolean fastbootEnabled)
Set the fastboot option for the device. Should be set when device is first allocated.
| Параметры | |
|---|---|
fastbootEnabled | boolean : whether fastboot is available for the device or not |
setFastbootPath
public 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.
| Параметры | |
|---|---|
fastbootPath | String |
setIDevice
public 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| Параметры | |
|---|---|
newDevice | IDevice : the IDevice |
setLogStartDelay
public void setLogStartDelay (int delay)
Sets the time in ms to wait before starting logcat capture for a online device.
| Параметры | |
|---|---|
delay | int : the delay in ms |
setOptions
public void setOptions (TestDeviceOptions options)
Set the TestDeviceOptions for the device
| Параметры | |
|---|---|
options | TestDeviceOptions |
setProperty
public boolean setProperty (String propKey,
String propValue)Sets the given property value on the device. Requires adb root is true.
| Параметры | |
|---|---|
propKey | String : The key targeted to be set. |
propValue | String : The property value to be set. |
| Возвраты | |
|---|---|
boolean | returns True if the setprop command was successful, False otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setRecovery
public void setRecovery (IDeviceRecovery recovery)
Set the IDeviceRecovery to use for this device. Should be set when device is first allocated.
| Параметры | |
|---|---|
recovery | IDeviceRecovery : the IDeviceRecovery |
setRecoveryMode
public 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| Параметры | |
|---|---|
mode | ITestDevice.RecoveryMode : whether 'recover till online only' mode should be on or not. |
setSetting
public void setSetting (String namespace,
String key,
String value) See setSetting(int,String,String,String) and performed on system user.
| Параметры | |
|---|---|
namespace | String |
key | String |
value | String |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setSetting
public 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"}
| Параметры | |
|---|---|
userId | int |
namespace | String |
key | String |
value | String |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setTestLogger
public void setTestLogger (ITestLogger testLogger)
Injects the ITestLogger instance
| Параметры | |
|---|---|
testLogger | ITestLogger |
setTrackingSerial
public void setTrackingSerial (String trackingSerial)
For device management purpose track the serial we use for referencing the device.
| Параметры | |
|---|---|
trackingSerial | String |
setUseFastbootErase
public void setUseFastbootErase (boolean useFastbootErase)
Set whether to use fastboot erase or fastboot format to wipe a partition on the device.
| Параметры | |
|---|---|
useFastbootErase | boolean : true if fastboot erase should be used or false if fastboot format should be used. |
startLogcat
public 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. startTradeInModeTesting
public boolean startTradeInModeTesting (int timeoutMs)
Enable testing trade-in mode. The device will be wiped and will reboot.
| Параметры | |
|---|---|
timeoutMs | int |
| Возвраты | |
|---|---|
boolean | True if we were successful, false otherwise |
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
startUser
public 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.
| Параметры | |
|---|---|
userId | int : of the user to start in the background |
| Возвраты | |
|---|---|
boolean | true if the user was successfully started in the background. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
startUser
public boolean startUser (int userId,
boolean waitFlag)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. Possible to provide extra flag to wait for the operation to have effect.
| Параметры | |
|---|---|
userId | int : of the user to start in the background |
waitFlag | boolean : will make the command wait until user is started and unlocked. |
| Возвраты | |
|---|---|
boolean | true if the user was successfully started in the background. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
startVisibleBackgroundUser
public boolean startVisibleBackgroundUser (int userId,
int displayId,
boolean waitFlag)Starts a given user in the background, visible in the given display (ie, allowing the user to launch activities in that display).
NOTE: this command doesn't check if the user exists, display is available, device supports such feature , etc.
| Параметры | |
|---|---|
userId | int : of the user to start in the background |
displayId | int : display to start user visible on |
waitFlag | boolean : will make the command wait until user is started and unlocked. |
| Возвраты | |
|---|---|
boolean | true if the user was successfully started visible in the background. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
stopEmulatorOutput
public void stopEmulatorOutput ()
Close and delete the emulator output.
stopLogcat
public 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.stopTradeInModeTesting
public void stopTradeInModeTesting ()
Stop trade-in mode testing.
| Броски | |
|---|---|
DeviceNotAvailableException | |
stopUser
public 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.
| Параметры | |
|---|---|
userId | int : of the user to stop. |
| Возвраты | |
|---|---|
boolean | true if the user was successfully stopped. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
stopUser
public 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.
| Параметры | |
|---|---|
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. |
| Возвраты | |
|---|---|
boolean | true if the user was successfully stopped. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
switchToAdbTcp
public String switchToAdbTcp ()
Switch device to adb-over-tcp mode.
| Возвраты | |
|---|---|
String | the tcp serial number or null if device could not be switched |
| Броски | |
|---|---|
DeviceNotAvailableException | |
switchToAdbUsb
public boolean switchToAdbUsb ()
Switch device to adb over usb mode.
| Возвраты | |
|---|---|
boolean | true if switch was successful, false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
switchUser
public boolean switchUser (int userId)
Switch to another userId with a default timeout. switchUser(int, long) .
| Параметры | |
|---|---|
userId | int |
| Возвраты | |
|---|---|
boolean | True if the new userId matches the userId provider. False otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
switchUser
public 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.
| Параметры | |
|---|---|
userId | int |
timeout | long : to wait before returning false for switch-user failed. |
| Возвраты | |
|---|---|
boolean | True if the new userId matches the userId provider. False otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
syncFiles
public 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.| Параметры | |
|---|---|
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 |
| Возвраты | |
|---|---|
boolean | true if files were synced successfully. false otherwise. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
takeBugreport
public 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 Bugreport.close() .
| Возвраты | |
|---|---|
Bugreport | |
uninstallPackage
public String uninstallPackage (String packageName)
Uninstall an Android package from device.
| Параметры | |
|---|---|
packageName | String : the Android package to uninstall |
| Возвраты | |
|---|---|
String | a String with an error code, or null if success. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
uninstallPackageForUser
public String uninstallPackageForUser (String packageName,
int userId)Uninstall an Android package from device for a given user.
| Параметры | |
|---|---|
packageName | String : the Android package to uninstall |
userId | int : the integer user id to uninstall for. |
| Возвраты | |
|---|---|
String | a String with an error code, or null if success. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
unlockDevice
public boolean unlockDevice ()
Unlocks the device if the device is in an encrypted state.
This method may restart the framework but will not callpostBootSetup() . Therefore, the device might not be fully ready to be tested when this method returns.| Возвраты | |
|---|---|
boolean | true if successful or if the device is unencrypted. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
waitForBootComplete
public boolean waitForBootComplete (long timeOut)
Blocks until the device's boot complete flag is set.
| Параметры | |
|---|---|
timeOut | long : time in msecs to wait for the flag to be set |
| Возвраты | |
|---|---|
boolean | true if device's boot complete flag is set within the timeout |
| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceAvailable
public boolean waitForDeviceAvailable ()
Waits for the device to be responsive and available for testing. Uses default timeout.
| Возвраты | |
|---|---|
boolean | True if device is available, False if recovery is disabled and unavailable. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceAvailable
public boolean waitForDeviceAvailable (long waitTime)
Waits for the device to be responsive and available for testing.
| Параметры | |
|---|---|
waitTime | long : the time in ms to wait |
| Возвраты | |
|---|---|
boolean | True if device is available, False if recovery is disabled and unavailable. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceAvailableInRecoverPath
public boolean waitForDeviceAvailableInRecoverPath (long waitTime)
Waits for the device to be responsive and available without considering recovery path.
| Параметры | |
|---|---|
waitTime | long |
| Возвраты | |
|---|---|
boolean | True if device is available, False if unavailable. |
| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceBootloader
public void waitForDeviceBootloader ()
Blocks until device is visible via fastboot. Use default timeout.
| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceInRecovery
public boolean waitForDeviceInRecovery (long waitTime)
Blocks for the device to be in the 'adb recovery' state (note this is distinct from IDeviceRecovery ).
| Параметры | |
|---|---|
waitTime | long : the time in ms to wait |
| Возвраты | |
|---|---|
boolean | true if device boots into recovery before time expires. false otherwise |
waitForDeviceInSideload
public boolean waitForDeviceInSideload (long waitTime)
Blocks for the device to be in the 'adb sideload' state
| Параметры | |
|---|---|
waitTime | long : the time in ms to wait |
| Возвраты | |
|---|---|
boolean | true if device boots into sideload before time expires. false otherwise |
waitForDeviceNotAvailable
public boolean waitForDeviceNotAvailable (long waitTime)
Blocks for the device to be not available ie missing from adb
| Параметры | |
|---|---|
waitTime | long : the time in ms to wait |
| Возвраты | |
|---|---|
boolean | true if device becomes not available before time expires. false otherwise |
waitForDeviceOnline
public void waitForDeviceOnline ()
Blocks until device is visible via adb. Uses default timeout
Note the device may not necessarily be responsive to commands on completion. UsewaitForDeviceAvailable() instead.| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceOnline
public void waitForDeviceOnline (long waitTime)
Blocks until device is visible via adb.
Note the device may not necessarily be responsive to commands on completion. UsewaitForDeviceAvailable() instead.| Параметры | |
|---|---|
waitTime | long : the time in ms to wait |
| Броски | |
|---|---|
DeviceNotAvailableException | |
waitForDeviceShell
public boolean waitForDeviceShell (long waitTime)
Waits for device to be responsive to a basic adb shell command.
| Параметры | |
|---|---|
waitTime | long : the time in ms to wait |
| Возвраты | |
|---|---|
boolean | true if device becomes responsive before waitTime elapses. |
Защищенные методы
addExtraConnectionBuilderArgs
protected void addExtraConnectionBuilderArgs (DefaultConnection.ConnectionBuilder builder)
| Параметры | |
|---|---|
builder | DefaultConnection.ConnectionBuilder |
buildAdbShellCommand
protected String[] buildAdbShellCommand (String command,
boolean forceExitStatusDetection,
boolean oldShellCommand)Builds the OS command for the given adb shell command session and args
| Параметры | |
|---|---|
command | String |
forceExitStatusDetection | boolean |
oldShellCommand | boolean |
| Возвраты | |
|---|---|
String[] | |
checkApiLevelAgainst
protected void checkApiLevelAgainst (String feature,
int strictMinLevel)| Параметры | |
|---|---|
feature | String |
strictMinLevel | int |
createRebootDeviceAction
protected NativeDevice.RebootDeviceAction createRebootDeviceAction (NativeDevice.RebootMode rebootMode, String reason)
Create a RebootDeviceAction to be used when performing a reboot action.
| Параметры | |
|---|---|
rebootMode | NativeDevice.RebootMode : a mode of this reboot. |
reason | String : for this reboot. |
| Возвраты | |
|---|---|
NativeDevice.RebootDeviceAction | the created RebootDeviceAction . |
doAdbReboot
protected void doAdbReboot (NativeDevice.RebootMode rebootMode, String reason)
Perform a adb reboot.
| Параметры | |
|---|---|
rebootMode | NativeDevice.RebootMode : a mode of this reboot. |
reason | String : for this reboot. |
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
ensureRuntimePermissionSupported
protected void ensureRuntimePermissionSupported ()
helper method to throw exception if runtime permission isn't supported
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
getApiLevelSafe
protected int getApiLevelSafe ()
| Возвраты | |
|---|---|
int | |
internalGetProperty
protected String internalGetProperty (String propName,
String fastbootVar,
String description)Fetch a device property, from the ddmlib cache by default, and falling back to either `adb shell getprop` or `fastboot getvar` depending on whether the device is in Fastboot or not.
| Параметры | |
|---|---|
propName | String : The name of the device property as returned by `adb shell getprop` |
fastbootVar | String : The name of the equivalent fastboot variable to query. if null , fastboot query will not be attempted |
description | String : A simple description of the variable. First letter should be capitalized. |
| Возвраты | |
|---|---|
String | A string, possibly null or empty, containing the value of the given property |
| Броски | |
|---|---|
DeviceNotAvailableException | |
UnsupportedOperationException | |
isInRebootCallback
protected boolean isInRebootCallback ()
Returns whether reboot callbacks is currently being executed or not. All public api's for reboot should be disabled if true.
| Возвраты | |
|---|---|
boolean | |
isNewer
protected 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.
| Параметры | |
|---|---|
localFile | File |
entry | IFileEntry |
| Возвраты | |
|---|---|
boolean | |
notifyRebootEnded
protected void notifyRebootEnded ()
Notifies all IDeviceActionReceiver about reboot end event.
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
notifyRebootStarted
protected void notifyRebootStarted ()
Notifies all IDeviceActionReceiver about reboot start event.
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
performDeviceAction
protected 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.
| Параметры | |
|---|---|
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 |
| Возвраты | |
|---|---|
boolean | true if action was performed successfully |
| Броски | |
|---|---|
DeviceNotAvailableException | if recovery attempt fails or max attempts done without success |
postAdbReboot
protected void postAdbReboot (NativeDevice.RebootMode rebootMode)
Possible extra actions that can be taken after a reboot.
| Параметры | |
|---|---|
rebootMode | NativeDevice.RebootMode |
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
prePostBootSetup
protected void prePostBootSetup ()
Allows each device type (AndroidNativeDevice, TestDevice) to override this method for specific post boot setup.
| Броски | |
|---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException | |
pullFileWithAdbCommand
protected boolean pullFileWithAdbCommand (String remoteFilePath,
File localFile,
long timeout)| Параметры | |
|---|---|
remoteFilePath | String |
localFile | File |
timeout | long |
| Возвраты | |
|---|---|
boolean | |
| Броски | |
|---|---|
DeviceNotAvailableException | |
setClock
protected void setClock (Clock clock)
Set the Clock instance to use.
| Параметры | |
|---|---|
clock | Clock |
setMicrodroidProcess
protected void setMicrodroidProcess (Process process)
Marks the TestDevice as microdroid and sets its CID.
| Параметры | |
|---|---|
process | Process : Process of the Microdroid VM. |
setTestDeviceOptions
protected void setTestDeviceOptions (Map<String, String> deviceOptions)
| Параметры | |
|---|---|
deviceOptions | Map |
simpleFastbootCommand
protected CommandResult simpleFastbootCommand (long timeout, String[] fullCmd)
Executes a simple fastboot command and report the status of the command.
| Параметры | |
|---|---|
timeout | long |
fullCmd | String |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
UnsupportedOperationException | |
simpleFastbootCommand
protected CommandResult simpleFastbootCommand (long timeout, Map<String, String> envVarMap, String[] fullCmd)
Executes a simple fastboot command with environment variables and report the status of the command.
| Параметры | |
|---|---|
timeout | long |
envVarMap | Map |
fullCmd | String |
| Возвраты | |
|---|---|
CommandResult | |
| Броски | |
|---|---|
UnsupportedOperationException | |
waitForDeviceNotAvailable
protected boolean waitForDeviceNotAvailable (String operationDesc,
long time)Wait to see the device going unavailable (stop reporting to adb).
| Параметры | |
|---|---|
operationDesc | String : The name of the operation that is waiting for unavailable. |
time | long : The time to wait for unavailable to occur. |
| Возвраты | |
|---|---|
boolean | True if device did become unavailable. |
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2026-06-22 UTC.