NativeDevice

public class NativeDevice
extends Object implements IConfigurationReceiver , IManagedTestDevice , ITestLoggerReceiver

java.lang.Object
com.android.tradefed.device.NativeDevice


Реализация по умолчанию ITestDevice для устройств Android с неполным стеком.

Краткое содержание

Вложенные классы

class NativeDevice.AdbAction

ERROR(DeviceAction/com.android.tradefed.device.NativeDevice.DeviceAction DeviceAction) при запуске команды ОС 'adb ....'.

class NativeDevice.AdbShellAction

class NativeDevice.RebootDeviceAction

ERROR(DeviceAction/com.android.tradefed.device.NativeDevice.DeviceAction DeviceAction) при перезагрузке устройства.

Константы

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)

Создает TestDevice .

Публичные методы

void batchPrefetchStartupBuildProps ()

Микрооптимизация (около 400 миллисекунд) за счет предварительной загрузки всех необходимых нам реквизитов вместо вызова «adb getprop» для каждого из них.

boolean canSwitchToHeadlessSystemUser ()

Возвращает информацию о том, разрешено ли переключиться на пользователя SYSTEM без графического интерфейса.

boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

Проверьте, поддерживается ли в настоящее время функция, учитывая минимально поддерживаемый уровень.

boolean checkConnectivity ()

Проверьте, подключено ли устройство к сети.

boolean clearErrorDialogs ()

Попытайтесь закрыть все диалоговые окна с ошибками, отображаемые в данный момент в пользовательском интерфейсе устройства.

void clearLastConnectedWifiNetwork ()

Очищает последнюю подключенную сеть Wi-Fi.

void clearLogcat ()

Удаляет все накопленные данные logcat.

boolean connectToWifiNetwork ( wifiSsidToPsk, boolean scanSsid)

Подключается к сети Wi-Fi.

boolean connectToWifiNetwork (String wifiSsid, String wifiPsk)

Подключается к сети Wi-Fi.

boolean connectToWifiNetwork ( wifiSsidToPsk)

Подключается к сети Wi-Fi.f

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

Подключается к сети Wi-Fi.

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

Вариант connectToWifiNetwork(String, String) , который подключается только в том случае, если устройство в данный момент не имеет подключения к сети.

boolean connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk)

Вариант connectToWifiNetwork(String, String) , который подключается только в том случае, если устройство в данный момент не имеет подключения к сети.

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)

Удаляет зарегистрированный IDeviceActionReceiver .

boolean deviceSoftRestarted ( ProcessInfo prevSystemServerProcess)

Вспомогательный метод для проверки того, был ли выполнен мягкий перезапуск устройства, путем сравнения текущего system_server с предыдущим system_server ProcessInfo .

boolean deviceSoftRestartedSince (long utcEpochTime, TimeUnit timeUnit)

Вспомогательный метод для проверки того, был ли выполнен мягкий перезапуск устройства с момента начала отсчета времени UTC с момента начала отсчета устройства и его ERROR(/TimeUnit) .

boolean disableAdbRoot ()

Отключает adb root.

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 ()

Включает adb root.

boolean enableNetworkMonitor ()

Включает сетевой мониторинг на устройстве.

String executeAdbCommand (long timeout, String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду с заданным тайм-аутом.

String executeAdbCommand (long timeout, envMap, String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду с заданным тайм-аутом.

String executeAdbCommand (String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду.

CommandResult executeAdbV2Command (String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду.

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

Вспомогательный метод, который выполняет команду adb как системную команду с заданным тайм-аутом.

CommandResult executeAdbV2Command (long timeout, envMap, String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду с заданным тайм-аутом.

CommandResult executeFastbootCommand (String... cmdArgs)

Вспомогательный метод, который выполняет команду fastboot как системную команду со временем ожидания по умолчанию 2 минуты.

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

Вспомогательный метод, который выполняет команду fastboot как системную команду.

CommandResult executeLongFastbootCommand (String... cmdArgs)

Вспомогательный метод, который выполняет длительную команду fastboot как системную команду.

CommandResult executeLongFastbootCommand ( envVarMap, String... cmdArgs)

Вспомогательный метод, который выполняет длительную команду fastboot как системную команду с системными переменными окружения.

String executeShellCommand (String command)

Вспомогательный метод, который выполняет команду оболочки adb и возвращает вывод в виде String .

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 должным образом заполненного выводом статуса команды, stdout и stderr.

CommandResult executeShellV2Command (String cmd, OutputStream pipeToOutput)

Вспомогательный метод, который выполняет команду оболочки adb и возвращает результаты в виде CommandResult должным образом заполненного выводом статуса команды и stderr.

CommandResult executeShellV2Command (String cmd, File pipeAsInput)

Вспомогательный метод, который выполняет команду оболочки adb и возвращает результаты в виде CommandResult должным образом заполненного выводом статуса команды, stdout и stderr.

CommandResult executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)

Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды.

CommandResult executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit)

Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды.

CommandResult executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)

Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды.

CommandResult executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts)

Выполняет команду оболочки adb с дополнительными параметрами для управления поведением команды.

CommandResult fastbootWipePartition (String partition)

Вспомогательный метод, который стирает раздел устройства.

getActiveApexes ()

Получите информацию об APEX, активированных на устройстве.

String getAdbPath ()

Возвращает путь к используемому двоичному файлу adb.

getAllSettings (String namespace)

Возвращает пары ключ-значение запрошенного пространства имен.

DeviceAllocationState getAllocationState ()

Возвращает текущее состояние распределения устройства.

String getAndroidId (int userId)

Найти и вернуть android-id, связанный с userId, или null, если не найден.

getAndroidIds ()

Создайте карту идентификаторов Android, соответствующих идентификаторам пользователей.

int getApiLevel ()

Получите уровень API устройства.

PackageInfo getAppPackageInfo (String packageName)

Получить информацию о пакете, установленном на устройстве.

getAppPackageInfos ()

Получить информацию о пакетах, установленных на устройстве.

String getBasebandVersion ()

Удобный метод получения версии этого устройства в диапазоне частот (радио).

Integer getBattery ()

Возвращает текущий уровень заряда батареи устройства или Null, если уровень заряда батареи недоступен.

boolean getBooleanProperty (String name, boolean defaultValue)

Возвращает логическое значение заданного свойства.

getBootHistory ()

Вспомогательный метод собирает карту истории загрузки с указанием времени и причины загрузки.

getBootHistorySince (long utcEpochTime, TimeUnit timeUnit)

Вспомогательный метод собирает карту истории загрузки с указанием времени и причины загрузки с указанного времени с момента начала эпохи устройства и указанной единицы времени.

String getBootloaderVersion ()

Удобный метод получения версии загрузчика этого устройства.

InputStreamSource getBugreport ()

Извлекает отчет об ошибке из устройства.

InputStreamSource getBugreportz ()

Извлекает отчет об ошибке с устройства.

String getBuildAlias ()

Получите псевдоним сборки, которую в данный момент выполняет устройство.

String getBuildFlavor ()

Получите версию сборки для устройства.

String getBuildId ()

Получите сборку, которую в данный момент выполняет устройство.

String getBuildSigningKeys ()

Возвращает тип ключа, используемый для подписи образа устройства.

Обычно устройства Android могут быть подписаны с помощью тестовых ключей (как в AOSP) или ключей выпуска (контролируемых отдельными производителями устройств).

DeviceDescriptor getCachedDeviceDescriptor ()

Возвращает кэшированный DeviceDescriptor если устройство выделено, в противном случае возвращает текущий DeviceDescriptor .

DeviceDescriptor getCachedDeviceDescriptor (boolean shortDescriptor)

Возвращает кэшированный DeviceDescriptor если устройство выделено, в противном случае возвращает текущий DeviceDescriptor .

String[] getChildren (String path)

Альтернатива использованию IFileEntry , которая иногда не работает из-за разрешений.

AbstractConnection getConnection ()

Текущее соединение, связанное с устройством.

ContentProviderHandler getContentProvider (int userId)

Возвращает ContentProviderHandler или null, если недоступно.

DeviceFoldableState getCurrentFoldableState ()

Возвращает текущее состояние складывания устройства или значение NULL, если возникли какие-то проблемы.

int getCurrentUser ()

Возвращает идентификатор текущего работающего пользователя.

String getDeviceClass ()

Получите класс устройства.

long getDeviceDate ()

Возвращает дату устройства в миллисекундах с начала эпохи.

DeviceDescriptor getDeviceDescriptor ()

Верните DeviceDescriptor из информации об устройстве, чтобы получить информацию о нем без передачи фактического объекта устройства.

DeviceDescriptor getDeviceDescriptor (boolean shortDescriptor)

Верните DeviceDescriptor из информации об устройстве, чтобы получить информацию о нем без передачи фактического объекта устройства.

TestDeviceState getDeviceState ()

Получить состояние устройства.

long getDeviceTimeOffset (Date date)

Помощник для получения разницы во времени между устройством и заданной ERROR(/Date) .

InputStreamSource getEmulatorOutput ()

Получить поток stdout и stderr эмулятора

Process getEmulatorProcess ()

Верните Process , соответствующий этому эмулятору.

final File getExecuteShellCommandLog ()

Журнал, содержащий все журналы executeShellCommand(String) .

long getExternalStoreFreeSpace ()

Вспомогательный метод для определения объема свободного места на внешнем хранилище устройства.

String getFastbootPath ()

Возвращает путь к используемому двоичному файлу fastboot.

String getFastbootProductType ()

Удобный метод получения типа продукта данного устройства, когда оно находится в режиме быстрой загрузки.

String getFastbootProductVariant ()

Удобный метод получения типа продукта данного устройства, когда оно находится в режиме быстрой загрузки.

String getFastbootSerialNumber ()

Возвращает серийный номер режима быстрой загрузки.

String getFastbootVariable (String variableName)

Извлечь заданное значение переменной fastboot из устройства.

String getFastbootVersion ()

Возвращает строку версии используемого двоичного файла fastboot.

IFileEntry getFileEntry (String path)

Получить ссылку на удаленный файл на устройстве.

IFileEntry getFileEntry ( FileListingService.FileEntry entry)

Неофициальный помощник для получения FileEntry из некорневого пути.

getFoldableStates ()

Возвращает список складных состояний устройства.

IDevice getIDevice ()

Возвращает ссылку на связанный ddmlib IDevice .

getInstalledPackageNames ()

Получите имена пакетов приложений, имеющихся на устройстве.

long getIntProperty (String name, long defaultValue)

Возвращает целочисленное значение заданного свойства устройства.

String getIpAddress ()

Получает IP-адрес устройства.

KeyguardControllerState getKeyguardState ()

Возвращает объект для получения текущего состояния блокировки клавиатуры или null, если не поддерживается.

long getLastExpectedRebootTimeMillis ()

Возвращает время последнего запуска перезагрузки API Tradefed в миллисекундах с момента EPOCH, как возвращено System.currentTimeMillis() .

int getLaunchApiLevel ()

Получите первый запущенный уровень API устройства.

InputStreamSource getLogcat ()

Захватывает поток снимков данных LogCat.

InputStreamSource getLogcat (int maxBytes)

Захватывает поток снимков последних maxBytes захваченных данных logcat.

InputStreamSource getLogcatDump ()

Получите дамп текущего журнала событий для устройства.

InputStreamSource getLogcatSince (long date)

Захватывает поток снимков захваченных данных LogCat, начиная с указанной даты.

String getMacAddress ()

Возвращает MAC-адрес устройства, null, если не удалось выполнить запрос с устройства.

Integer getMainUserId ()

Возвращает основной идентификатор пользователя.

getMainlineModuleInfo ()

Получите информацию об основных модулях, установленных на устройстве.

int getMaxNumberOfRunningUsersSupported ()

Получите максимальное количество поддерживаемых одновременно работающих пользователей.

int getMaxNumberOfUsersSupported ()

Получите максимальное количество поддерживаемых пользователей.

Process getMicrodroidProcess ()
IDeviceStateMonitor getMonitor ()

Верните IDeviceStateMonitor , связанный с устройством.

String getMountPoint (String mountName)

Возвращает точку монтирования.

ITestDevice.MountPointInfo getMountPointInfo (String mountpoint)

Возвращает MountPointInfo соответствующий указанному пути точки монтирования, или null если по этому пути ничего не смонтировано или он не отображается в /proc/mounts как точка монтирования.

getMountPointInfo ()

Возвращает проанализированную версию информации из /proc/mounts на устройстве.

TestDeviceOptions getOptions ()

Получите параметры тестирования для устройства.

long getPartitionFreeSpace (String partition)

Вспомогательный метод для определения объема свободного места на разделе устройства.

Integer getPrimaryUserId ()

Возвращает основной идентификатор пользователя.

ProcessInfo getProcessByName (String processName)

Вспомогательный метод выполняет команды «pidof» и «stat» и возвращает объект ProcessInfo с PID и временем начала указанного процесса.

String getProcessPid (String process)

Возвращает pid службы или null, если что-то пошло не так.

String getProductType ()

Удобный способ узнать тип продукта данного устройства.

String getProductVariant ()

Удобный способ получить вариант товара этого устройства.

String getProperty (String name)

Извлечь заданное значение свойства из устройства.

ITestDevice.RecoveryMode getRecoveryMode ()

Получите текущий режим восстановления, используемый для устройства.

InputStreamSource getScreenshot (long displayId)

Делает снимок экрана с устройства с заданным идентификатором дисплея.

InputStreamSource getScreenshot (String format)

Делает снимок экрана с устройства.

InputStreamSource getScreenshot (String format, boolean rescale)

Делает снимок экрана с устройства.

InputStreamSource getScreenshot ()

Делает снимок экрана с устройства.

String getSerialNumber ()

Удобный способ получить серийный номер данного устройства.

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

Верните значение запрошенного параметра.

String getSetting (String namespace, String key)

См. getSetting(int, String, String) и выполняется для системного пользователя.

String getSimOperator ()

Возвращает оператора SIM-карты или null, если карта недоступна или устройство недоступно.

String getSimState ()

Возвращает состояние SIM-карты или null, если она недоступна или устройство недоступно.

getTombstones ()

Извлечь и вернуть список объектов-надгробий с устройств.

long getTotalMemory ()

Возвращает общий размер физической памяти в байтах или -1 в случае внутренней ошибки.

String getTrackingSerial ()

Для управления устройством получите серийный номер, используемый для отслеживания устройства.

getUninstallablePackageNames ()

Получите имена пакетов приложений, которые можно удалить.

boolean getUseFastbootErase ()

Узнайте, следует ли использовать fastboot erasure или fastboot format для очистки раздела на устройстве.

int getUserFlags (int userId)

Найти и вернуть флаги заданного пользователя.

getUserInfos ()

Получает сопоставление useId с UserInfo на устройстве.

int getUserSerialNumber (int userId)

Возвращает серийный номер, связанный с идентификатором пользователя, если он найден, или -10000 в любых других случаях.

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, String... extraArgs)

Установите пакет Android на устройство.

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

Установите пакет Android на устройство.

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

Установить пакет Android на устройство для указанного пользователя.

String installPackageForUser (File packageFile, boolean reinstall, boolean grantPermissions, 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 ()

Верните, доступна ли для устройства функция fastboot.

boolean isHeadless ()

Возвращает значение true, если устройство не имеет экрана, в противном случае — false.

boolean isHeadlessSystemUserMode ()

Возвращает информацию о том, использует ли устройство режим пользователя без графического интерфейса.

boolean isMainUserPermanentAdmin ()

Возвращает, является ли основной пользователь постоянным администратором и не может ли он быть удален или понижен до статуса, отличного от администратора.

boolean isMultiUserSupported ()

Определяет, поддерживается ли многопользовательский режим.

boolean isPackageInstalled (String packageName, String userId)

Запросите у устройства заданное имя пакета и заданный идентификатор пользователя, чтобы проверить, установлен ли он в данный момент для этого пользователя.

boolean isPackageInstalled (String packageName)

Запросите у устройства заданное имя пакета, чтобы проверить, установлен ли он в данный момент или нет.

boolean isRuntimePermissionSupported ()

Проверьте, поддерживает ли платформа на устройстве предоставление разрешений во время выполнения.

boolean isStateBootloaderOrFastbootd ()

Возвращает true, если устройство находится в состоянии TestDeviceState.FASTBOOT или TestDeviceState.FASTBOOTD .

boolean isUserRunning (int userId)

Проверьте, запущен ли данный пользователь.

boolean isUserSecondary (int userId)

Возвращает, является ли указанный пользователь вторичным пользователем в соответствии с его флагами.

boolean isUserVisible (int userId)

Проверяет, виден ли указанный пользователь.

boolean isUserVisibleOnDisplay (int userId, int displayId)

Проверяет, виден ли заданный пользователь на заданном дисплее.

boolean isVisibleBackgroundUsersOnDefaultDisplaySupported ()

Возвращает, позволяет ли устройство запускать видимых пользователей в фоновом режиме в ERROR(/java.android.view.Display#DEFAULT_DISPLAY) .

boolean isVisibleBackgroundUsersSupported ()

Возвращает, позволяет ли устройство запускать пользователей в фоновом режиме.

boolean isWifiEnabled ()

Проверьте, включен ли Wi-Fi.

listDisplayIds ()

Соберите список доступных идентификаторов дисплеев на устройстве, как сообщает «dumpsys SurfaceFlinger».

listDisplayIdsForStartingVisibleBackgroundUsers ()

Получает список дисплеев, которые можно использовать для start a user visible in the background .

listUsers ()

Получает список пользователей на устройстве.

boolean logAnrs ( ITestLogger logger)

Собирает и регистрирует ANR-ошибки с устройства.

boolean logBugreport (String dataName, ITestLogger listener)

Вспомогательный метод для создания отчета об ошибке и его передачи авторам отчетов.

void logOnDevice (String tag, Log.LogLevel level, String format, Object... args)

Зарегистрируйте сообщение в журнале событий устройства.

void mountDebugfs ()

Смонтировать debugfs.

void nonBlockingReboot ()

Выдает команду на перезагрузку устройства и возвращает управление после завершения команды, а также когда устройство больше не видно adb.

void postAdbRootAction ()

Переопределить, если устройству необходимо выполнить какие-либо особые действия после выполнения adb root и перед тем, как устройство снова будет подключено к сети.

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 pullFile (String remoteFilePath, File localFile)

Извлекает файл с устройства.

File pullFile (String remoteFilePath, int userId)

Извлекает файл с устройства, сохраняет его в локальном временном ERROR(/File) и возвращает этот File .

File pullFile (String remoteFilePath)

Извлекает файл с устройства, сохраняет его в локальном временном ERROR(/File) и возвращает этот File .

boolean pullFile (String remoteFilePath, File localFile, int userId)

Извлекает файл с устройства.

String pullFileContents (String remoteFilePath)

Извлекает файл с устройства и возвращает его содержимое.

File pullFileFromExternal (String remoteFilePath)

Удобный метод для извлечения файла из внешнего хранилища устройства, сохранения его в локальном временном ERROR(/File) и возврата ссылки на этот File .

boolean pushDir (File localFileDir, String deviceFilePath, excludedDirectories)

Рекурсивно отправить содержимое каталога на устройство, исключая некоторые отфильтрованные каталоги.

boolean pushDir (File localFileDir, String deviceFilePath)

Рекурсивно отправить содержимое каталога на устройство.

boolean pushDir (File localFileDir, String deviceFilePath, int userId)

Рекурсивно отправить содержимое каталога на устройство.

boolean pushFile (File localFile, String remoteFilePath, boolean evaluateContentProviderNeeded)

Вариант pushFile(File, String) , который может при необходимости учитывать оценку потребности в поставщике контента.

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 с указанием reason , которая будет сохраняться после перезагрузки.

void reboot ()

Перезагружает устройство в режим adb.

void rebootIntoBootloader ()

Перезагружает устройство в режим загрузчика.

void rebootIntoFastbootd ()

Перезагружает устройство в режим fastbootd.

void rebootIntoRecovery ()

Перезагружает устройство в режим восстановления adb.

void rebootIntoSideload ()

Перезагружает устройство в режим adb sideload (обратите внимание, что это специальный режим при восстановлении)

Блокируется до тех пор, пока устройство не перейдет в режим боковой загрузки

void rebootIntoSideload (boolean autoReboot)

Перезагружает устройство в режим adb sideload (обратите внимание, что это специальный режим при восстановлении)

Блокируется до тех пор, пока устройство не перейдет в режим боковой загрузки

void rebootUntilOnline ()

Альтернатива reboot() , которая блокирует только до тех пор, пока устройство не будет подключено к сети, т.е. станет видимым для adb.

void rebootUntilOnline (String reason)

Альтернатива reboot() , которая блокирует только до тех пор, пока устройство не будет подключено к сети, т.е. станет видимым для adb.

void rebootUserspace ()

Перезагружает только пользовательскую часть устройства.

void rebootUserspaceUntilOnline ()

Альтернатива rebootUserspace() ()}, которая блокирует только до тех пор, пока устройство не будет подключено к сети, т.е. станет видимым для adb.

boolean recoverDevice ()

Попытки восстановить связь с устройством.

void registerDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver)

Регистрирует IDeviceActionReceiver для этого устройства.

void remountSystemReadOnly ()

Сделайте системный раздел на устройстве доступным только для чтения.

void remountSystemWritable ()

Сделайте системный раздел на устройстве доступным для записи.

void remountVendorReadOnly ()

Сделайте раздел поставщика на устройстве доступным только для чтения.

void remountVendorWritable ()

Сделайте раздел поставщика на устройстве доступным для записи.

boolean removeAdmin (String componentName, int userId)

Удалить администратора данного устройства для данного пользователя и вернуть true в случае успешного завершения, в противном случае false .

void removeOwners ()

Удалите всех существующих владельцев профилей устройств, приложив все усилия.

boolean removeUser (int userId)

Удалить указанного пользователя с устройства.

void resetContentProviderSetup ()

Чтобы снова активировать настройку поставщика контента, сбросьте флаг.

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

Удобный метод для выполнения ERROR(/#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection)) с одним или несколькими прослушивателями, переданными в качестве параметров.

boolean runInstrumentationTests ( IRemoteAndroidTestRunner runner, listeners)

Проводит испытания приборов и обеспечивает восстановление устройств.

boolean runInstrumentationTestsAsUser ( IRemoteAndroidTestRunner runner, int userId, listeners)

То же, что ERROR(ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner, Collection)/com.android.tradefed.device.ITestDevice#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection) ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner, Collection)) но запускает тест для данного пользователя.

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

То же, что и ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner, ITestLifeCycleReceiver...) , но запускает тест для заданного пользователя.

void setAdbPath (String adbPath)

Задает путь к двоичному файлу adb, который следует использовать.

void setConfiguration ( IConfiguration configuration)

Внедряет используемую IConfiguration .

final void setConnectionAvdInfo ( GceAvdInfo avdInfo)
void setDate (Date date)

Устанавливает дату на устройстве

Примечание: для установки даты на устройстве требуются права root.

boolean setDeviceOwner (String componentName, int userId)

Установить компонент администратора устройства в качестве владельца устройства для данного пользователя.

void setDeviceState ( TestDeviceState deviceState)

Обновите состояние устройства.

void setEmulatorOutputStream ( SizeLimitedOutputStream output)

Для эмулятора установите SizeLimitedOutputStream для вывода лога

void setEmulatorProcess (Process p)

Устанавливает Process , когда данное устройство является эмулятором.

void setFastbootEnabled (boolean fastbootEnabled)

Установите опцию быстрой загрузки для устройства.

void setFastbootPath (String fastbootPath)

Задает путь к двоичному файлу fastboot, который следует использовать.

void setIDevice ( IDevice newDevice)

Обновите IDevice, связанный с этим ITestDevice.

void setLogStartDelay (int delay)

Устанавливает время ожидания в мс перед началом сбора данных logcat для подключенного к сети устройства.

void setOptions ( TestDeviceOptions options)

Установите TestDeviceOptions для устройства

boolean setProperty (String propKey, String propValue)

Устанавливает заданное значение свойства на устройстве.

void setRecovery ( IDeviceRecovery recovery)

Настройте IDeviceRecovery для использования на этом устройстве.

void setRecoveryMode ( ITestDevice.RecoveryMode mode)

Установите текущий режим восстановления для устройства.

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

См. setSetting(int, String, String, String) и выполняется для системного пользователя.

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

Добавить значение настройки в пространство имен данного пользователя.

void setTestLogger ( ITestLogger testLogger)

Внедряет экземпляр ITestLogger

void setTrackingSerial (String trackingSerial)

Для управления устройством отслеживайте серийный номер, который мы используем для обозначения устройства.

void setUseFastbootErase (boolean useFastbootErase)

Укажите, следует ли использовать функцию fastboot erasure или 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 ()

Берет отчет об ошибке и возвращает его внутрь объекта Bugreport для его обработки.

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» (обратите внимание, что это отличается от IDeviceRecovery ).

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)

Создает команду ОС для заданного сеанса команды оболочки adb и аргументов

void checkApiLevelAgainst (String feature, int strictMinLevel)
NativeDevice.RebootDeviceAction createRebootDeviceAction ( NativeDevice.RebootMode rebootMode, String reason)

Создайте RebootDeviceAction , который будет использоваться при выполнении действия перезагрузки.

IRunUtil createRunUtil ()
void doAdbReboot ( NativeDevice.RebootMode rebootMode, String reason)

Выполните перезагрузку adb.

void ensureRuntimePermissionSupported ()

вспомогательный метод для создания исключения, если разрешение во время выполнения не поддерживается

int getApiLevelSafe ()
ITestLogger getLogger ()
IRunUtil getRunUtil ()

Получите экземпляр RunUtil для использования.

String internalGetProperty (String propName, String fastbootVar, String description)

Извлечь свойство устройства из кэша ddmlib по умолчанию и использовать либо `adb shell getprop`, либо `fastboot getvar` в зависимости от того, находится ли устройство в режиме быстрой загрузки или нет.

boolean isInRebootCallback ()

Возвращает, выполняются ли в данный момент обратные вызовы перезагрузки или нет.

boolean isNewer (File localFile, IFileEntry entry)

Возвращает true если локальный файл новее удаленного файла.

void notifyRebootEnded ()

Уведомляет все IDeviceActionReceiver о событии завершения перезагрузки.

void notifyRebootStarted ()

Уведомляет все IDeviceActionReceiver о событии начала перезагрузки.

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

Выполняет действие на этом устройстве.

void postAdbReboot ( NativeDevice.RebootMode rebootMode)

Возможные дополнительные действия, которые можно предпринять после перезагрузки.

void prePostBootSetup ()

Позволяет каждому типу устройства (AndroidNativeDevice, TestDevice) переопределять этот метод для конкретной настройки после загрузки.

boolean pullFileInternal (String remoteFilePath, File localFile)
void setClock (Clock clock)

Установите используемый экземпляр Clock.

void setMicrodroidProcess (Process process)

Отмечает TestDevice как microdroid и устанавливает его CID.

void setTestDeviceOptions ( deviceOptions)
CommandResult simpleFastbootCommand (long timeout, envVarMap, String[] fullCmd)

Выполняет простую команду fastboot с переменными среды и сообщает статус команды.

CommandResult simpleFastbootCommand (long timeout, String[] fullCmd)

Выполняет простую команду fastboot и сообщает о состоянии команды.

boolean waitForDeviceNotAvailable (String operationDesc, long time)

Дождитесь, пока устройство станет недоступным (прекратит отправлять отчеты в adb).

Константы

DEBUGFS_PATH

public static final String DEBUGFS_PATH

Постоянное значение: "/sys/kernel/debug"

НЕВЕРНЫЙ_ИДЕНТИФИКАТОР_ПОЛЬЗОВАТЕЛЯ

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/"

ХРАНЕНИЕ_ЭМУЛЯЦИЯ

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 для информирования об изменениях состояния распределения. Может быть пустым.

Публичные методы

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

checkConnectivity

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() возвращает только данные журнала, созданные после определенного момента (например, после перепрошивки новой сборки устройства и т. д.).

connectToWifiNetwork

public boolean connectToWifiNetwork ( wifiSsidToPsk, 
                boolean scanSsid)

Подключается к сети Wi-Fi.

Включает Wi-Fi и блокирует его до успешного подключения к одной из сетей Wi-Fi, указанных в карте wifiSsidToPsk. После установки соединения экземпляр будет пытаться восстановить его после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork() .

Параметры
wifiSsidToPsk : Карта SSID сетей Wi-Fi и паролей.

scanSsid boolean : следует ли сканировать скрытые SSID для этой сети.

Возврат
boolean true если подключение к сети Wi-Fi успешно. false в противном случае.

Броски
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork (String wifiSsid, 
                String wifiPsk)

Подключается к сети Wi-Fi.

Включает Wi-Fi и блокирует подключение до успешного подключения к указанной сети Wi-Fi. После установки подключения экземпляр будет пытаться восстановить его после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork() .

Параметры
wifiSsid String : SSID Wi-Fi для подключения

wifiPsk String : пароль PSK или null, если не зашифровано

Возврат
boolean true если подключение к сети Wi-Fi успешно. false в противном случае.

Броски
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork ( wifiSsidToPsk)

Подключается к сети Wi-Fi.

Включает Wi-Fi и блокирует его до успешного подключения к одной из сетей Wi-Fi, указанных в карте wifiSsidToPsk. После установки соединения экземпляр будет пытаться восстановить его после каждой перезагрузки, пока не будет вызван ITestDevice.disconnectFromWifi() или ITestDevice.clearLastConnectedWifiNetwork()

Параметры
wifiSsidToPsk : Карта SSID сетей Wi-Fi и паролей.

Возврат
boolean true если подключение к сети Wi-Fi успешно. false в противном случае.

Броски
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork (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 для этой сети.

Возврат
boolean true если подключение к сети Wi-Fi успешно. false в противном случае.

Броски
DeviceNotAvailableException

Подключиться к сети Wi-Fi, если необходимо

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

Вариант connectToWifiNetwork(String, String) , который подключается только в том случае, если устройство в данный момент не имеет подключения к сети.

Параметры
scanSsid boolean : нужно ли сканировать скрытые SSID для этой сети

Возврат
boolean true если подключение к сети Wi-Fi успешно. false в противном случае.

Броски
DeviceNotAvailableException

Подключиться к сети Wi-Fi, если необходимо

public boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk)

Вариант connectToWifiNetwork(String, String) , который подключается только в том случае, если устройство в данный момент не имеет подключения к сети.

Возврат
boolean true если подключение к сети Wi-Fi успешно. false в противном случае.

Броски
DeviceNotAvailableException

createUser

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

Создайте пользователя с заданным именем и предоставленными флагами.

Параметры
name String : пользователя для создания на устройстве

guest boolean : включить пользовательский флаг --guest во время создания

ephemeral boolean : включить пользовательский флаг --ephemeral во время создания

Возврат
int идентификатор созданного пользователя

Броски
DeviceNotAvailableException

createUser

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

createUser

public int createUser (String name)

Создайте пользователя с заданным именем и флагами по умолчанию 0.

Параметры
name String : пользователя для создания на устройстве

Возврат
int целое число для созданного идентификатора пользователя

Броски
DeviceNotAvailableException

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 с момента возникновения ERROR(/TimeUnit) . Мягкий перезапуск означает перезапуск system_server вне периода полной перезагрузки устройства (например, запрошенной перезагрузки). Текущее значение utcEpochTime устройства в миллисекундах можно получить с помощью метода getDeviceDate() .

Параметры
utcEpochTime long : время устройства в секундах с начала эпохи.

timeUnit TimeUnit : единица времени TimeUnit для заданного utcEpochTime.

Возврат
boolean true если устройство перезапущено

Броски
DeviceNotAvailableException

отключитьAdbRoot

public boolean disableAdbRoot ()

Отключает adb root.

Отключение root-доступа к adb может привести к отключению устройства от adb. Этот метод блокирует устройство до тех пор, пока оно не станет доступно.

Возврат
boolean true в случае успеха.

Броски
DeviceNotAvailableException

отключить защиту клавиатуры

public void disableKeyguard ()

Попытки отключить блокировку клавиатуры.

Сначала дождитесь готовности отправки ввода. Это происходит примерно в то же время, когда устройство сообщает BOOT_COMPLETE, по-видимому, асинхронно, поскольку в текущей реализации фреймворка иногда возникают состояния гонки. Затем отправляется команда на отключение защиты клавиатуры (работает только на незащищённых устройствах).

Броски
DeviceNotAvailableException

отключить NetworkMonitor

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)

Вспомогательный метод для определения существования файла на устройстве.

Параметры
deviceFilePath String : абсолютный путь к файлу на устройстве для проверки.

Возврат
boolean true если файл существует, в противном случае false .

Броски
DeviceNotAvailableException

dumpHeap

public File dumpHeap (String process, 
                String devicePath)

Попытайтесь создать дамп кучи из system_server. Вызывающая сторона обязана очистить дамп.

Параметры
process String : имя процесса устройства, на котором будет выполнено дампирование.

devicePath String : путь на устройстве, куда следует сохранить дамп. Это должно быть место, где это разрешено правами доступа.

Возврат
File ERROR(/File) , содержащий отчёт. Значение NULL, если что-то не удалось.

Броски
DeviceNotAvailableException

enableAdbRoot

public boolean enableAdbRoot ()

Включает root-доступ через adb. Если параметр «enable-root» установлен в значение «false», выведет сообщение в журнал и вернётся без включения root-доступа.

Включение root-доступа к adb может привести к отключению устройства от adb. Этот метод блокирует работу устройства до тех пор, пока оно не станет доступно.

Возврат
boolean true в случае успеха.

Броски
DeviceNotAvailableException

enableNetworkMonitor

public boolean enableNetworkMonitor ()

Включает сетевой мониторинг на устройстве.

Возврат
boolean true если мониторинг успешно включен. false если мониторинг не удался.

Броски
DeviceNotAvailableException

выполнитьAdbCommand

public String executeAdbCommand (long timeout, 
                String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду с заданным тайм-аутом.

Вместо этого везде, где это возможно, следует использовать executeShellCommand(String) , поскольку этот метод обеспечивает лучшее обнаружение сбоев и производительность.

Параметры
timeout long : время в миллисекундах, по истечении которого устройство будет считаться неотвечающим, 0L — без тайм-аута

cmdArgs String : команда adb и аргументы для запуска

Возврат
String стандартный вывод команды. null если команда не была выполнена.

Броски
DeviceNotAvailableException

выполнитьAdbCommand

public String executeAdbCommand (long timeout, 
                 envMap, 
                String... cmdArgs)

Вспомогательный метод, который выполняет команду adb как системную команду с заданным тайм-аутом.

Вместо этого везде, где это возможно, следует использовать executeShellCommand(String) , поскольку этот метод обеспечивает лучшее обнаружение сбоев и производительность.

Параметры
timeout long : время в миллисекундах, по истечении которого устройство будет считаться неотвечающим, 0L — без тайм-аута

envMap : среда, устанавливаемая для команды

cmdArgs String : команда adb и аргументы для запуска

Возврат
String стандартный вывод команды. null если команда не была выполнена.

Броски
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

выполнитьAdbV2Command

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

выполнитьAdbV2Command

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

выполнитьAdbV2Command

public CommandResult executeAdbV2Command (long timeout, 
                 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 : environment to set for the command

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

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

executeLongFastbootCommand

public CommandResult executeLongFastbootCommand (String... cmdArgs)

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

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

Параметры
cmdArgs String : the fastboot command and arguments to run

Возврат
CommandResult the CommandResult containing output of command

Броски
DeviceNotAvailableException

executeLongFastbootCommand

public CommandResult executeLongFastbootCommand ( 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 : 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

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 of executeShellCommand(String, com.android.ddmlib.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, 
                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 : ERROR(/OutputStream) where the std output will be redirected, or null.

Возврат
CommandResult The result in 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 ERROR(/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, 
                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, 
                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 ERROR(/File) that will be piped as input to the command, or null.

pipeToOutput OutputStream : ERROR(/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, 
                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 ERROR(/File) that will be piped as input to the command, or null.

pipeToOutput OutputStream : ERROR(/OutputStream) where the std output will be redirected, or null.

pipeToError OutputStream : ERROR(/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

fastbootWipePartition

public CommandResult fastbootWipePartition (String partition)

Helper method which wipes a partition for the device.

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

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

Параметры
partition String : the partition to wipe

Возврат
CommandResult the CommandResult containing output of command

Броски
DeviceNotAvailableException

getActiveApexes

public  getActiveApexes ()

Fetch the information about APEXes activated on the device.

Возврат
ERROR(/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  getAllSettings (String namespace)

Return key value pairs of requested namespace.

Параметры
namespace String : must be one of {"system", "secure", "global"}

Возврат
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  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 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

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  getAppPackageInfos ()

Fetch information of packages installed on the device.

Возврат
ERROR(/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

getBattery

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  getBootHistory ()

Helper method collects the boot history map with boot time and boot reason.

Возврат
Map of boot time (UTC time in second since Epoch) and boot reason

Броски
DeviceNotAvailableException

getBootHistorySince

public  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 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

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 ERROR(/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

получить текущего пользователя

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 ERROR(/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 generic getProductType() 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

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 generic getProductType() 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

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

getFastbootVersion

public String getFastbootVersion ()

Returns the version string of the fastboot binary being used. Or null if something goes wrong.

Возврат
String

получитьFileEntry

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

получитьFileEntry

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  getFoldableStates ()

Returns the list of foldable states on the device. Can be obtained with "cmd device_state print-states".

Возврат

Броски
DeviceNotAvailableException

getIDevice

public IDevice getIDevice ()

Returns a reference to the associated ddmlib IDevice .

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

Возврат
IDevice the IDevice

getInstalledPackageNames

public  getInstalledPackageNames ()

Fetch the application package names present on the device.

Возврат
ERROR(/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

getIpAddress

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.

Works in two modes:

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

    Возврат
    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

    getMacAddress

    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  getMainlineModuleInfo ()

    Get the information about the mainline modules installed on the device.

    Возврат
    ERROR(/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 ()

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

    Возврат
    int an integer indicating the number of supported 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)

    Возвращает точку монтирования.

    Queries the device directly if the cached info in IDevice 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 ERROR(/List) of MountPointInfo containing the information in "/proc/mounts"

    Броски
    DeviceNotAvailableException

    getMountPointInfo

    public  getMountPointInfo ()

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

    Возврат
    A ERROR(/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

    получитьProductType

    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

    получитьПроперти

    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.

    получить скриншот

    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

    получить скриншот

    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

    получить скриншот

    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

    получить скриншот

    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

    получитьсерийный номер

    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  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.

    Возврат
    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  getUninstallablePackageNames ()

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

    Возврат
    ERROR(/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  getUserInfos ()

    Gets the Map of useId to UserInfo on the device. Will throw DeviceRuntimeException if output from device is not as expected.

    Возврат
    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

    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, 
                    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 String с кодом ошибки или null в случае успеха.

    Броски
    DeviceNotAvailableException

    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 String с кодом ошибки или null в случае успеха.

    Броски
    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 String с кодом ошибки или null в случае успеха.

    Броски
    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 String с кодом ошибки или null в случае успеха.

    Броски
    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 ()

    isAdbRoot

    public boolean isAdbRoot ()

    Возврат
    boolean

    Броски
    DeviceNotAvailableException

    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 ()

    Determines if multi user is supported.

    Возврат
    boolean true if multi user is supported, false otherwise

    Броски
    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

    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  listDisplayIds ()

    Collect the list of available displays id on the device as reported by "dumpsys SurfaceFlinger".

    Возврат
    The list of displays. Default always returns the default display 0.

    Броски
    DeviceNotAvailableException

    listDisplayIdsForStartingVisibleBackgroundUsers

    public  listDisplayIdsForStartingVisibleBackgroundUsers ()

    Gets the list of displays that can be used to start a user visible in the background .

    Возврат

    Броски
    DeviceNotAvailableException

    listUsers

    public  listUsers ()

    Gets the list of users on the device. Will throw DeviceRuntimeException if output from device is not as expected.

    Возврат
    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().

    mountDebugfs

    public void mountDebugfs ()

    Mount debugfs.

    Броски
    DeviceNotAvailableException

    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

    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 ERROR(/File) , and returns that File .

    Параметры
    remoteFilePath String : the absolute path to file on device.

    userId int : The user id to pull from

    Возврат
    File A ERROR(/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 ERROR(/File) , and returns that File .

    Параметры
    remoteFilePath String : the absolute path to file on device.

    Возврат
    File A ERROR(/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 ERROR(/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 ERROR(/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, 
                     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 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

    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

    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 propety.

    Параметры
    reason String : a reason for this reboot, or null if no reason is specified.

    Броски
    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

    rebootIntoFastbootd

    public void rebootIntoFastbootd ()

    Reboots the device into fastbootd mode.

    Blocks until device is in fastbootd mode.

    Броски
    DeviceNotAvailableException

    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

    removeAdmin

    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, 
                    ITestLifeCycleReceiver... listeners)

    Convenience method for performing ERROR(/#runInstrumentationTests(com.android.ddmlib.testrunner.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

    runInstrumentationTests

    public boolean runInstrumentationTests (IRemoteAndroidTestRunner runner, 
                     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 : 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

    runInstrumentationTestsAsUser

    public boolean runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, 
                    int userId, 
                     listeners)

    Same as ERROR(ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner, Collection)/com.android.tradefed.device.ITestDevice#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection) ITestDevice.runInstrumentationTests(IRemoteAndroidTestRunner, Collection)) but runs the test for the given user.

    Параметры
    runner IRemoteAndroidTestRunner

    userId int

    listeners

    Возврат
    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 String с кодом ошибки или null в случае успеха.

    Броски
    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 String с кодом ошибки или null в случае успеха.

    Броски
    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 call postBootSetup() . 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

    unmountDebugfs

    public void unmountDebugfs ()

    Unmount debugfs.

    Броски
    DeviceNotAvailableException

    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

    waitForDeviceFastbootD

    public void waitForDeviceFastbootD ()

    Броски
    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. Use waitForDeviceAvailable() 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. Use waitForDeviceAvailable() 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)

    Builds the OS command for the given adb shell command session and args

    Параметры
    command String

    forceExitStatusDetection 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 .

    createRunUtil

    protected IRunUtil createRunUtil ()

    Возврат
    IRunUtil

    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

    получитьЛоггер

    protected ITestLogger getLogger ()

    Возврат
    ITestLogger

    getRunUtil

    protected IRunUtil getRunUtil ()

    Get the RunUtil instance to use.

    Возврат
    IRunUtil

    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

    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

    pullFileInternal

    protected boolean pullFileInternal (String remoteFilePath, 
                    File localFile)

    Параметры
    remoteFilePath String

    localFile File

    Возврат
    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 ( deviceOptions)

    Параметры
    deviceOptions

    simpleFastbootCommand

    protected CommandResult simpleFastbootCommand (long timeout, 
                     envVarMap, 
                    String[] fullCmd)

    Executes a simple fastboot command with environment variables and report the status of the command.

    Параметры
    timeout long

    envVarMap

    fullCmd String

    Возврат
    CommandResult

    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

    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.