Нативное устройство

public class NativeDevice
extends Object implements IManagedTestDevice , IConfigurationReceiver , ITestLoggerReceiver

java.lang.Объект
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) для перезагрузки устройства.

Константы

int INVALID_USER_ID

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

long MAX_HOST_DEVICE_TIME_OFFSET

int MAX_RETRY_ATTEMPTS

количество попыток выполнения команды по умолчанию

Поля

protected static final String SD_CARD

protected static final String STORAGE_EMULATED

protected TestDeviceOptions mOptions

protected final IDeviceStateMonitor mStateMonitor

Публичные конструкторы

NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)

Создает TestDevice .

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

boolean canSwitchToHeadlessSystemUser ()

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

boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

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

boolean checkConnectivity ()

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

boolean clearErrorDialogs ()

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

void clearLastConnectedWifiNetwork ()

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

void clearLogcat ()

Удаляет любые накопленные данные logcat.

boolean connectToWifiNetwork ( wifiSsidToPsk, boolean scanSsid) connectToWifiNetwork ( wifiSsidToPsk, boolean scanSsid)

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

boolean connectToWifiNetwork (String wifiSsid, String wifiPsk)

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

boolean connectToWifiNetwork ( wifiSsidToPsk) 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.

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) executeAdbCommand (long timeout, envMap, String... cmdArgs)

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

String executeAdbCommand (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) executeLongFastbootCommand ( envVarMap, String... cmdArgs)

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

String executeShellCommand (String command)

Вспомогательный метод, который выполняет команду оболочки adb и возвращает вывод в виде ERROR(/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.

getAllSettings (String namespace)

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

DeviceAllocationState getAllocationState ()

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

String getAndroidId (int userId)

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

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

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

DeviceFoldableState getCurrentFoldableState ()

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

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

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

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

getInstalledPackageNames ()

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

long getIntProperty (String name, long defaultValue)

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

String getIpAddress ()

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

KeyguardControllerState getKeyguardState ()

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

long getLastExpectedRebootTimeMillis ()

Возвращает последний раз, когда API-интерфейсы Tradefed инициировали перезагрузку в миллисекундах с момента EPOCH, возвращаемого ERROR(/System#currentTimeMillis()) .

int getLaunchApiLevel ()

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

InputStreamSource getLogcat ()

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

InputStreamSource getLogcat (int maxBytes)

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

InputStreamSource getLogcatDump ()

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

InputStreamSource getLogcatSince (long date)

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

String getMacAddress ()

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

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 службы или ноль, если что-то пошло не так.

String getProductType ()

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

String getProductVariant ()

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

String getProperty (String name)

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

ITestDevice.RecoveryMode getRecoveryMode ()

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

InputStreamSource getScreenshot (String format)

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

InputStreamSource getScreenshot (long displayId)

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

InputStreamSource getScreenshot (String format, boolean rescale)

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

InputStreamSource getScreenshot ()

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

String getSerialNumber ()

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

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

Возвращает значение запрошенной настройки.

String getSetting (String namespace, String key)

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

String getSimOperator ()

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

String getSimState ()

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

getTombstones ()

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

long getTotalMemory ()

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

getUninstallablePackageNames ()

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

boolean getUseFastbootErase ()

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

int getUserFlags (int userId)

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

getUserInfos ()

Получает карту useId для UserInfo на устройстве.

int getUserSerialNumber (int userId)

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

IManagedTestDevice.DeviceEventResponse handleAllocationEvent (DeviceEvent event)

Обработайте данное DeviceEvent .

Обработать событие DeviceEvent, которое может перевести или не перевести это устройство в новое состояние распределения.

boolean hasFeature (String feature)

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

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

boolean isAdbTcp ()
boolean isAppEnumerationSupported ()

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

boolean isBypassLowTargetSdkBlockSupported ()

Проверьте, поддерживает ли платформа на устройстве обход нижнего целевого блока SDK при установке приложения.

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)

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

void nonBlockingReboot ()

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

void postAdbRootAction ()

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

void postAdbUnrootAction ()

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

void postBootSetup ()

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

void postInvocationTearDown (Throwable exception)

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

void preInvocationSetup ( IBuildInfo info, MultiMap <String, String> attributes)

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

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) pushDir (File localFileDir, String deviceFilePath, excludedDirectories)

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

boolean pushDir (File localFileDir, String deviceFilePath)

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

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

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

boolean pushFile (File localFile, String remoteFilePath)

Отправьте файл на устройство.

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

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

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) runInstrumentationTests (IRemoteAndroidTestRunner runner, listeners)

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

boolean runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, int userId, listeners) 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 setConfiguration ( IConfiguration configuration)

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

void setDate (Date date)

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

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

boolean setDeviceOwner (String componentName, int userId)

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

void setDeviceState ( TestDeviceState deviceState)

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

void setEmulatorOutputStream ( SizeLimitedOutputStream output)

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

void setEmulatorProcess (Process p)

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

void setFastbootEnabled (boolean fastbootEnabled)

Установите параметр fastboot для устройства.

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 setUseFastbootErase (boolean useFastbootErase)

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

void startLogcat ()

Начните захват вывода logcat с устройства в фоновом режиме.

boolean startUser (int userId)

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

boolean startUser (int userId, boolean waitFlag)

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

boolean startVisibleBackgroundUser (int userId, int displayId, boolean waitFlag)

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

void stopEmulatorOutput ()

Закройте и удалите вывод эмулятора.

void stopLogcat ()

Остановить захват выходных данных logcat с устройства и удалить текущие сохраненные данные logcat.

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

Разблокирует устройство, если оно находится в зашифрованном состоянии.

boolean waitForBootComplete (long timeOut)

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

boolean waitForDeviceAvailable ()

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

boolean waitForDeviceAvailable (long waitTime)

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

boolean waitForDeviceAvailableInRecoverPath (long waitTime)

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

void waitForDeviceBootloader ()

Блокирует, пока устройство не будет видно через fastboot.

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.

Защищенные методы

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 для использования.

void initializeConnection ( IBuildInfo info, MultiMap <String, String> attributes)
String internalGetProperty (String propName, String fastbootVar, String description)

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

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

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

void prePostBootSetup ()

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

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

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

void setMicrodroidProcess (Process process)

Помечает TestDevice как микродроид и устанавливает его CID.

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

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

CommandResult simpleFastbootCommand (long timeout, String[] fullCmd)

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

boolean waitForDeviceNotAvailable (String operationDesc, long time)

Подождите, пока устройство станет недоступным (перестаньте сообщать adb).

Константы

INVALID_USER_ID

public static final int INVALID_USER_ID

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

Постоянное значение: -10000 (0xffffd8f0)

MAX_HOST_DEVICE_TIME_OFFSET

protected static final long MAX_HOST_DEVICE_TIME_OFFSET

Постоянное значение: 5000 (0x0000000000001388)

MAX_RETRY_ATTEMPTS

protected static final int MAX_RETRY_ATTEMPTS

количество попыток выполнения команды по умолчанию

Постоянное значение: 2 (0x00000002)

Поля

SD CARD

protected static final String SD_CARD

STORAGE_EMULATED

protected static final String STORAGE_EMULATED

mОпции

protected TestDeviceOptions mOptions

мстатемонитор

protected final IDeviceStateMonitor mStateMonitor

Публичные конструкторы

Нативное устройство

public NativeDevice (IDevice device, 
                IDeviceStateMonitor stateMonitor, 
                IDeviceMonitor allocationMonitor)

Создает TestDevice .

Параметры
device IDevice : связанный IDevice

stateMonitor IDeviceStateMonitor : механизм IDeviceStateMonitor для использования

allocationMonitor IDeviceMonitor : IDeviceMonitor для информирования об изменениях состояния распределения. Может быть нулевым

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

можетSwitchToHeadlessSystemUser

public boolean canSwitchToHeadlessSystemUser ()

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

Возвращает
boolean

Броски
DeviceNotAvailableException

проверитьApiLevelAgainstNextRelease

public boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

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

Параметры
strictMinLevel int : строгий минимально возможный уровень, который поддерживает эту функцию.

Возвращает
boolean Истинно, если уровень поддерживается. Ложь в противном случае.

Броски
DeviceNotAvailableException

проверитьПодключение

public boolean checkConnectivity ()

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

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

Броски
DeviceNotAvailableException

ClearErrorDialogs

public boolean clearErrorDialogs ()

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

Возвращает
boolean true , если диалоги отсутствовали или диалоги были успешно очищены. false в противном случае.

Броски
DeviceNotAvailableException

ClearLastConnectedWifiNetwork

public void clearLastConnectedWifiNetwork ()

Очищает последнюю подключенную сеть Wi-Fi. Это следует вызывать при запуске нового вызова, чтобы избежать подключения к сети Wi-Fi, использованной в предыдущем тесте, после перезагрузки устройства.

очиститьLogcat

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 : Wi-Fi ssid для подключения

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

Возвращает
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 : Wi-Fi ssid для подключения

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

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

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

Броски
DeviceNotAvailableException

ConnectToWifiNetworkIfNeeded

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

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

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

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

Броски
DeviceNotAvailableException

ConnectToWifiNetworkIfNeeded

public boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk)

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

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

Броски
DeviceNotAvailableException

Создать пользователя

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

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

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

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

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

Возвращает
int id созданного пользователя

Броски
DeviceNotAvailableException

Создать пользователя

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

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

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

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

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

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

Возвращает
int id созданного пользователя

Броски
DeviceNotAvailableException

Создать пользователя

public int createUser (String name)

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

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

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

Броски
DeviceNotAvailableException

создатьUserNoThrow

public int createUserNoThrow (String name)

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

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

Возвращает
int целое число для созданного идентификатора пользователя или -1 для ошибки.

Броски
DeviceNotAvailableException

удалить файл

public void deleteFile (String deviceFilePath)

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

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

Броски
DeviceNotAvailableException

отменить регистрациюDeviceActionReceiver

public void deregisterDeviceActionReceiver (IDeviceActionReceiver deviceActionReceiver)

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

Параметры
deviceActionReceiver IDeviceActionReceiver : IDeviceActionReceiver , который будет удален.

устройствоSoftRestarted

public boolean deviceSoftRestarted (ProcessInfo prevSystemServerProcess)

Вспомогательный метод для проверки мягкого перезапуска устройства путем сравнения текущего system_server с предыдущим system_server ProcessInfo . Используйте getProcessByName(String) для получения ProcessInfo .

Параметры
prevSystemServerProcess ProcessInfo : предыдущий процесс system_server ProcessInfo .

Возвращает
boolean true , если устройство мягко перезапущено

Броски
DeviceNotAvailableException

устройствоSoftRestartedSince

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.

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

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

Броски
DeviceNotAvailableException

отключитьKeyguard

public void disableKeyguard ()

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

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

Броски
DeviceNotAvailableException

отключитьсетевоймонитор

public boolean disableNetworkMonitor ()

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

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

Броски
DeviceNotAvailableException

отключить от Wi-Fi

public boolean disconnectFromWifi ()

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

Удаляет все сети из списка известных сетей и отключает Wi-Fi.

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

Броски
DeviceNotAvailableException

делаетFileExist

public boolean doesFileExist (String deviceFilePath, 
                int userId)

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

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

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

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

Броски
DeviceNotAvailableException

делаетFileExist

public boolean doesFileExist (String deviceFilePath)

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

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

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

Броски
DeviceNotAvailableException

дампКуча

public File dumpHeap (String process, 
                String devicePath)

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

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

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

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

Броски
DeviceNotAvailableException

включитьAdbRoot

public boolean enableAdbRoot ()

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

Включение adb root может привести к отключению устройства от 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

выполнитьAdbCommand

public String executeAdbCommand (String... cmdArgs)

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

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

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

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

Броски
DeviceNotAvailableException

выполнить FastbootCommand

public CommandResult executeFastbootCommand (String... cmdArgs)

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

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

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

Возвращает
CommandResult CommandResult, содержащий вывод команды

Броски
DeviceNotAvailableException

выполнить FastbootCommand

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

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

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

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

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

Возвращает
CommandResult CommandResult, содержащий вывод команды

Броски
DeviceNotAvailableException

выполнить команду LongFastboot

public CommandResult executeLongFastbootCommand (String... cmdArgs)

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

Идентичен executeFastbootCommand(String) за исключением того, что используется более длительный тайм-аут.

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

Возвращает
CommandResult CommandResult, содержащий вывод команды

Броски
DeviceNotAvailableException

выполнить команду LongFastboot

public CommandResult executeLongFastbootCommand ( envVarMap, 
                String... cmdArgs)

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

Идентичен executeFastbootCommand(String) за исключением того, что используется более длительный тайм-аут.

Параметры
envVarMap : переменные системной среды, с которыми запускается команда fastboot

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

Возвращает
CommandResult CommandResult, содержащий вывод команды

Броски
DeviceNotAvailableException

выполнитьShellCommand

public String executeShellCommand (String command)

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

Параметры
command String : команда оболочки adb для запуска

Возвращает
String вывод оболочки

Броски
DeviceNotAvailableException

выполнитьShellCommand

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

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

Параметры
command String : команда оболочки adb для запуска

receiver IShellOutputReceiver : IShellOutputReceiver для прямого вывода оболочки.

maxTimeToOutputShellResponse long : максимальное количество времени, в течение которого команда может не выводить никакого ответа; единица измерения, указанная в timeUnit

timeUnit TimeUnit : единица измерения для maxTimeToOutputShellResponse

retryAttempts int : максимальное количество попыток повторения команды в случае сбоя из-за исключения. DeviceNotResponsiveException будет сгенерировано, если retryAttempts не увенчались успехом.

Броски
DeviceNotAvailableException

выполнитьShellCommand

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

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

Параметры
command String : команда оболочки adb для запуска

receiver IShellOutputReceiver : IShellOutputReceiver для прямого вывода оболочки.

maxTimeoutForCommand long : максимальный тайм-аут для завершения команды; единица измерения, указанная в timeUnit

maxTimeToOutputShellResponse long : максимальное количество времени, в течение которого команда может не выводить никакого ответа; единица измерения, указанная в 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

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

getCurrentFoldableState

public DeviceFoldableState getCurrentFoldableState ()

Returns the current foldable state of the device or null if some issues occurred.

Возвращает
DeviceFoldableState

Броски
DeviceNotAvailableException

getCurrentUser

public int getCurrentUser ()

Return the id of the current running user. In case of error, return -10000.

Возвращает
int

Броски
DeviceNotAvailableException

getDeviceClass

public String getDeviceClass ()

Get the device class.

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

получитьDeviceDescriptor

public DeviceDescriptor getDeviceDescriptor ()

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

Возвращает
DeviceDescriptor

получитьDeviceDescriptor

public DeviceDescriptor getDeviceDescriptor (boolean shortDescriptor)

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

Параметры
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 ERROR(/Process) corresponding to this emulator.

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

getFileEntry

public IFileEntry getFileEntry (String path)

Retrieve a reference to a remote file on device.

Параметры
path String : the file path to retrieve. Can be an absolute path or path relative to '/'. (ie both "/system" and "system" syntax is supported)

Возвращает
IFileEntry the IFileEntry or null if file at given path cannot be found

Броски
DeviceNotAvailableException

getFileEntry

public IFileEntry getFileEntry (FileListingService.FileEntry entry)

Unofficial helper to get a FileEntry from a non-root path. FIXME: Refactor the FileEntry system to have it available from any path. (even non root).

Параметры
entry FileListingService.FileEntry : a FileEntry not necessarily root as Ddmlib requires.

Возвращает
IFileEntry a FileEntryWrapper representing the FileEntry.

Броски
com.android.tradefed.device.DeviceNotAvailableException
DeviceNotAvailableException

getFoldableStates

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

    Returns a mount point.

    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

    getOptions

    public TestDeviceOptions getOptions ()

    Fetch the test options for the device.

    Возвращает
    TestDeviceOptions TestDeviceOptions related to the device under test.

    getPartitionFreeSpace

    public long getPartitionFreeSpace (String partition)

    Helper method to determine amount of free space on device partition.

    Параметры
    partition String

    Возвращает
    long the amount of free space in KB

    Броски
    DeviceNotAvailableException

    getPrimaryUserId

    public Integer getPrimaryUserId ()

    Returns the primary user id.

    Возвращает
    Integer the userId of the primary user if there is one, and null if there is no primary user.

    Броски
    DeviceNotAvailableException

    getProcessByName

    public ProcessInfo getProcessByName (String processName)

    Helper method runs the "pidof" and "stat" command and returns ProcessInfo object with PID and process start time of the given process.

    Параметры
    processName String : the proces name String.

    Возвращает
    ProcessInfo ProcessInfo of given processName

    Броски
    DeviceNotAvailableException

    getProcessPid

    public String getProcessPid (String process)

    Returns the pid of the service or null if something went wrong.

    Параметры
    process String : The proces name String.

    Возвращает
    String

    Броски
    DeviceNotAvailableException

    getProductType

    public String getProductType ()

    Convenience method to get the product type of this device.

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

    Возвращает
    String the ERROR(/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 ERROR(/String) product variant name or null if it cannot be determined

    Броски
    DeviceNotAvailableException

    getProperty

    public String getProperty (String name)

    Retrieve the given property value from the device.

    Параметры
    name String : the property name

    Возвращает
    String the property value or null if it does not exist

    Броски
    DeviceNotAvailableException

    getRecoveryMode

    public ITestDevice.RecoveryMode getRecoveryMode ()

    Get the current recovery mode used for the device.

    Возвращает
    ITestDevice.RecoveryMode the current recovery mode used for the device.

    getScreenshot

    public InputStreamSource getScreenshot (String format)

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

    Параметры
    format String : supported PNG, JPEG

    Возвращает
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    Броски
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot (long displayId)

    Grabs a screenshot from the device given display id. Format is PNG.

    TODO: extend the implementations above to support 'format' and 'rescale'

    Параметры
    displayId long : the display id of the screen to get screenshot from.

    Возвращает
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    Броски
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot (String format, 
                    boolean rescale)

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

    Параметры
    format String : supported PNG, JPEG

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

    Возвращает
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    Броски
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot ()

    Grabs a screenshot from the device.

    Возвращает
    InputStreamSource a InputStreamSource of the screenshot in png format, or null if the screenshot was not successful.

    Броски
    DeviceNotAvailableException

    getSerialNumber

    public String getSerialNumber ()

    Convenience method to get serial number of this device.

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

    получитьнадгробия

    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.

    Возвращает
    Список файлов надгробий, пустой, если надгробий нет.

    Броски
    DeviceNotAvailableException

    getTotalMemory

    public long getTotalMemory ()

    Returns total physical memory size in bytes or -1 in case of internal error

    Возвращает
    long

    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 ERROR(/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: " or " " directly.

    Возвращает
    boolean True if feature is found, false otherwise.

    Броски
    DeviceNotAvailableException

    installPackage

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

    Install an Android package on device.

    Параметры
    packageFile File : the apk file to install

    reinstall boolean : true if a reinstall should be performed

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

    Возвращает
    String a ERROR(/String) with an error code, or null if success.

    Броски
    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 a ERROR(/String) with an error code, or null if success.

    Броски
    DeviceNotAvailableException

    installPackageForUser

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

    Install an Android package on device for a given user.

    Параметры
    packageFile File : the apk file to install

    reinstall boolean : true if a reinstall should be performed

    userId int : the integer user id to install for.

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

    Возвращает
    String a ERROR(/String) with an error code, or null if success.

    Броски
    DeviceNotAvailableException

    installPackageForUser

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

    Install an Android package on device for a given user.

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

    Параметры
    packageFile File : the apk file to install

    reinstall boolean : true if a reinstall should be performed

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

    userId int : the integer user id to install for.

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

    Возвращает
    String a ERROR(/String) with an error code, or null if success.

    Броски
    DeviceNotAvailableException

    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

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

    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)

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

    Параметры
    exception Throwable : если есть, последнее исключение, вызванное сбоем вызова.

    preInvocationSetup

    public void preInvocationSetup (IBuildInfo info, 
                    MultiMap<String, String> attributes)

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

    Параметры
    info IBuildInfo : IBuildInfo устройства.

    attributes MultiMap : атрибуты, хранящиеся в контексте вызова.

    Броски
    DeviceNotAvailableException
    TargetSetupError

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

    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

    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

    reboot

    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

    reboot

    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

    восстановитьустройство

    public boolean recoverDevice ()

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

    Возвращает
    boolean True, если попытка восстановления выполнена успешно, возвращает False, если восстановление было пропущено.

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

    remountSystemWritable

    public void remountSystemWritable ()

    Make the system partition on the device writable. 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

    setConfiguration

    public void setConfiguration (IConfiguration configuration)

    Injects the IConfiguration in use.

    Параметры
    configuration IConfiguration

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

    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.

    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.

    stopUser

    public boolean stopUser (int userId)

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

    Параметры
    userId int : of the user to stop.

    Возвращает
    boolean true if the user was successfully stopped.

    Броски
    DeviceNotAvailableException

    stopUser

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

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

    Параметры
    userId int : of the user to stop.

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

    forceFlag boolean : will force stop the user.

    Возвращает
    boolean true if the user was successfully stopped.

    Броски
    DeviceNotAvailableException

    switchToAdbTcp

    public String switchToAdbTcp ()

    Switch device to adb-over-tcp mode.

    Возвращает
    String the tcp serial number or null if device could not be switched

    Броски
    DeviceNotAvailableException

    switchToAdbUsb

    public boolean switchToAdbUsb ()

    Switch device to adb over usb mode.

    Возвращает
    boolean true if switch was successful, false otherwise.

    Броски
    DeviceNotAvailableException

    switchUser

    public boolean switchUser (int userId)

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

    Параметры
    userId int

    Возвращает
    boolean True if the new userId matches the userId provider. False otherwise.

    Броски
    DeviceNotAvailableException

    switchUser

    public boolean switchUser (int userId, 
                    long timeout)

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

    Параметры
    userId int

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

    Возвращает
    boolean True if the new userId matches the userId provider. False otherwise.

    Броски
    DeviceNotAvailableException

    syncFiles

    public boolean syncFiles (File localFileDir, 
                    String deviceFilePath)

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

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

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

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

    Параметры
    localFileDir File : the local file directory containing files to recursively push.

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

    Возвращает
    boolean true if files were synced successfully. false otherwise.

    Броски
    DeviceNotAvailableException

    takeBugreport

    public Bugreport takeBugreport ()

    Take a bugreport and returns it inside a Bugreport object to handle it. Return null in case of issue. File referenced in the Bugreport object need to be cleaned via Bugreport.close() .

    Возвращает
    Bugreport

    uninstallPackage

    public String uninstallPackage (String packageName)

    Uninstall an Android package from device.

    Параметры
    packageName String : the Android package to uninstall

    Возвращает
    String a ERROR(/String) with an error code, or null if success.

    Броски
    DeviceNotAvailableException

    uninstallPackageForUser

    public String uninstallPackageForUser (String packageName, 
                    int userId)

    Uninstall an Android package from device for a given user.

    Параметры
    packageName String : the Android package to uninstall

    userId int : the integer user id to uninstall for.

    Возвращает
    String a ERROR(/String) with an error code, or null if success.

    Броски
    DeviceNotAvailableException

    unlockDevice

    public boolean unlockDevice ()

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

    This method may restart the framework but will not 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

    waitForBootComplete

    public boolean waitForBootComplete (long timeOut)

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

    Параметры
    timeOut long : time in msecs to wait for the flag to be set

    Возвращает
    boolean true if device's boot complete flag is set within the timeout

    Броски
    DeviceNotAvailableException

    waitForDeviceAvailable

    public boolean waitForDeviceAvailable ()

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

    Возвращает
    boolean True if device is available, False if recovery is disabled and unavailable.

    Броски
    DeviceNotAvailableException

    waitForDeviceAvailable

    public boolean waitForDeviceAvailable (long waitTime)

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

    Параметры
    waitTime long : the time in ms to wait

    Возвращает
    boolean True if device is available, False if recovery is disabled and unavailable.

    Броски
    DeviceNotAvailableException

    waitForDeviceAvailableInRecoverPath

    public boolean waitForDeviceAvailableInRecoverPath (long waitTime)

    Waits for the device to be responsive and available without considering recovery path.

    Параметры
    waitTime long

    Возвращает
    boolean True if device is available, False if unavailable.

    Броски
    DeviceNotAvailableException

    waitForDeviceBootloader

    public void waitForDeviceBootloader ()

    Blocks until device is visible via fastboot. Use default timeout.

    Броски
    DeviceNotAvailableException

    waitForDeviceInRecovery

    public boolean waitForDeviceInRecovery (long waitTime)

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

    Параметры
    waitTime long : the time in ms to wait

    Возвращает
    boolean true if device boots into recovery before time expires. false otherwise

    waitForDeviceInSideload

    public boolean waitForDeviceInSideload (long waitTime)

    Blocks for the device to be in the 'adb sideload' state

    Параметры
    waitTime long : the time in ms to wait

    Возвращает
    boolean true if device boots into sideload before time expires. false otherwise

    waitForDeviceNotAvailable

    public boolean waitForDeviceNotAvailable (long waitTime)

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

    Параметры
    waitTime long : the time in ms to wait

    Возвращает
    boolean true if device becomes not available before time expires. false otherwise

    waitForDeviceOnline

    public void waitForDeviceOnline ()

    Blocks until device is visible via adb. Uses default timeout

    Note the device may not necessarily be responsive to commands on completion. 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.

    Защищенные методы

    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 : режим этой перезагрузки.

    reason String : для этой перезагрузки.

    Возвращает
    NativeDevice.RebootDeviceAction the created RebootDeviceAction .

    createRunUtil

    protected IRunUtil createRunUtil ()

    Возвращает
    IRunUtil

    doAdbReboot

    protected void doAdbReboot (NativeDevice.RebootMode rebootMode, 
                    String reason)

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

    Параметры
    rebootMode NativeDevice.RebootMode : режим этой перезагрузки.

    reason String : для этой перезагрузки.

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

    getLogger

    protected ITestLogger getLogger ()

    Возвращает
    ITestLogger

    getRunUtil

    protected IRunUtil getRunUtil ()

    Get the RunUtil instance to use.

    Возвращает
    IRunUtil

    initializeConnection

    protected void initializeConnection (IBuildInfo info, 
                    MultiMap<String, String> attributes)

    Параметры
    info IBuildInfo

    attributes MultiMap

    Броски
    DeviceNotAvailableException
    TargetSetupError

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

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

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