Dispositivo nativo

public class NativeDevice
extends Object implements IManagedTestDevice , IConfigurationReceiver , ITestLoggerReceiver

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


Implementação padrão de um dispositivo Android de pilha não completa ITestDevice .

Resumo

Classes aninhadas

class NativeDevice.AdbAction

Um ERROR(DeviceAction/com.android.tradefed.device.NativeDevice.DeviceAction DeviceAction) para executar um comando 'adb ....' do sistema operacional.

class NativeDevice.AdbShellAction

class NativeDevice.RebootDeviceAction

ERROR(DeviceAction/com.android.tradefed.device.NativeDevice.DeviceAction DeviceAction) para reiniciar um dispositivo.

Constantes

int INVALID_USER_ID

Valor retornado para qualquer id de usuário inválido/não encontrado: UserHandle definiu o valor -10000

long MAX_HOST_DEVICE_TIME_OFFSET

int MAX_RETRY_ATTEMPTS

o número padrão de tentativas de repetição de comando para executar

Campos

protected static final String SD_CARD

protected static final String STORAGE_EMULATED

protected TestDeviceOptions mOptions

protected final IDeviceStateMonitor mStateMonitor

Construtores públicos

NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)

Cria um TestDevice .

Métodos públicos

void batchPrefetchStartupBuildProps ()

Micro otimização (cerca de 400 millis) pré-buscando todos os props que precisamos, em vez de chamar 'adb getprop' para cada um.

boolean canSwitchToHeadlessSystemUser ()

Retorna se é permitido alternar para o usuário headless SYSTEM.

boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

Verifique se um recurso é ou não suportado no momento, dado um nível minimamente suportado.

boolean checkConnectivity ()

Verifique se o dispositivo tem conectividade de rede.

boolean clearErrorDialogs ()

Tente descartar todas as caixas de diálogo de erro atualmente exibidas na interface do usuário do dispositivo.

void clearLastConnectedWifiNetwork ()

Limpa a última rede wi-fi conectada.

void clearLogcat ()

Exclui todos os dados logcat acumulados.

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

Conecta-se a uma rede wi-fi.

boolean connectToWifiNetwork (String wifiSsid, String wifiPsk)

Conecta-se a uma rede wi-fi.

boolean connectToWifiNetwork ( wifiSsidToPsk) connectToWifiNetwork ( wifiSsidToPsk)

Conecta-se a uma rede wi-fi.f

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

Conecta-se a uma rede wi-fi.

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

Uma variante de connectToWifiNetwork(String, String) que só conecta se o dispositivo não tiver conectividade de rede no momento.

boolean connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk)

Uma variante de connectToWifiNetwork(String, String) que só conecta se o dispositivo não tiver conectividade de rede no momento.

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

Crie um usuário com um determinado nome e os sinalizadores fornecidos

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

Crie um usuário com um determinado nome e os sinalizadores fornecidos

int createUser (String name)

Crie um usuário com um determinado nome e sinalizadores padrão 0.

int createUserNoThrow (String name)

Crie um usuário com um determinado nome e sinalizadores padrão 0.

void deleteFile (String deviceFilePath)

Método auxiliar para excluir um arquivo ou diretório no dispositivo.

void deregisterDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver)

Remove o IDeviceActionReceiver registrado.

boolean deviceSoftRestarted ( ProcessInfo prevSystemServerProcess)

Método auxiliar para verificar se o dispositivo reiniciou por software comparando o system_server atual com o system_server anterior ProcessInfo .

boolean deviceSoftRestartedSince (long utcEpochTime, TimeUnit timeUnit)

Método auxiliar para verificar se o dispositivo reiniciou por software desde a hora UTC desde a época do dispositivo e seu ERROR(/TimeUnit) .

boolean disableAdbRoot ()

Desativa o adb root.

void disableKeyguard ()

Tenta desativar a proteção do teclado.

boolean disableNetworkMonitor ()

Desativa o monitoramento de rede no dispositivo.

boolean disconnectFromWifi ()

Desconecta de uma rede wi-fi.

boolean doesFileExist (String deviceFilePath, int userId)

Método auxiliar para determinar se o arquivo no dispositivo existe para um determinado usuário.

boolean doesFileExist (String deviceFilePath)

Método auxiliar para determinar se o arquivo no dispositivo existe.

File dumpHeap (String process, String devicePath)

Tente despejar o heap do system_server.

boolean enableAdbRoot ()

Ativa adb root.

boolean enableNetworkMonitor ()

Ativa o monitoramento de rede no dispositivo.

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

Método auxiliar que executa um comando adb como um comando do sistema com um tempo limite especificado.

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

Método auxiliar que executa um comando adb como um comando do sistema com um tempo limite especificado.

String executeAdbCommand (String... cmdArgs)

Método auxiliar que executa um comando adb como um comando do sistema.

CommandResult executeFastbootCommand (String... cmdArgs)

Método auxiliar que executa um comando fastboot como um comando do sistema com um tempo limite padrão de 2 minutos.

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

Método auxiliar que executa um comando fastboot como um comando do sistema.

CommandResult executeLongFastbootCommand (String... cmdArgs)

Método auxiliar que executa um comando fastboot de longa duração como um comando do sistema.

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

Método auxiliar que executa um comando de inicialização rápida de longa duração como um comando do sistema com variáveis ​​de ambiente do sistema.

String executeShellCommand (String command)

Método auxiliar que executa um comando shell adb e retorna a saída como uma String .

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

Executa um comando shell adb, com mais parâmetros para controlar o comportamento do comando.

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

Executa um comando shell adb, com mais parâmetros para controlar o comportamento do comando.

void executeShellCommand (String command, IShellOutputReceiver receiver)

Executa o comando adb shell fornecido, tentando várias vezes se o comando falhar.

CommandResult executeShellV2Command (String cmd)

Método auxiliar que executa um comando adb shell e retorna os resultados como um CommandResult preenchido corretamente com a saída de status do comando, stdout e stderr.

CommandResult executeShellV2Command (String cmd, OutputStream pipeToOutput)

Método auxiliar que executa um comando shell adb e retorna os resultados como um CommandResult preenchido corretamente com a saída de status do comando e stderr.

CommandResult executeShellV2Command (String cmd, File pipeAsInput)

Método auxiliar que executa um comando adb shell e retorna os resultados como um CommandResult preenchido corretamente com a saída de status do comando, stdout e stderr.

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

Executa um comando shell adb, com mais parâmetros para controlar o comportamento do comando.

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

Executa um comando shell adb, com mais parâmetros para controlar o comportamento do comando.

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

Executa um comando shell adb, com mais parâmetros para controlar o comportamento do comando.

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

Executa um comando shell adb, com mais parâmetros para controlar o comportamento do comando.

CommandResult fastbootWipePartition (String partition)

Método auxiliar que limpa uma partição do dispositivo.

getActiveApexes ()

Busque as informações sobre os APEXes ativados no dispositivo.

getAllSettings (String namespace)

Retorna pares de valores-chave do namespace solicitado.

DeviceAllocationState getAllocationState ()

Retorna o estado de alocação atual do dispositivo

String getAndroidId (int userId)

Encontre e retorne o android-id associado a um userId, nulo se não for encontrado.

getAndroidIds ()

Crie um mapa de IDs de Android encontrados correspondentes a IDs de usuário.

int getApiLevel ()

Obtenha o nível de API do dispositivo.

PackageInfo getAppPackageInfo (String packageName)

Busca informações sobre um pacote instalado no dispositivo.

getAppPackageInfos ()

Busca informações de pacotes instalados no dispositivo.

String getBasebandVersion ()

Método de conveniência para obter a versão de banda base (rádio) deste dispositivo.

Integer getBattery ()

Retorna o nível atual da bateria de um dispositivo ou Nulo se o nível da bateria estiver indisponível.

boolean getBooleanProperty (String name, boolean defaultValue)

Retorna o valor booleano da propriedade especificada.

getBootHistory ()

O método auxiliar coleta o mapa do histórico de inicialização com o tempo de inicialização e o motivo da inicialização.

getBootHistorySince (long utcEpochTime, TimeUnit timeUnit)

O método auxiliar coleta o mapa do histórico de inicialização com o tempo de inicialização e o motivo da inicialização desde o tempo determinado desde a época do dispositivo e a unidade de tempo especificada.

String getBootloaderVersion ()

Método de conveniência para obter a versão do carregador de inicialização deste dispositivo.

InputStreamSource getBugreport ()

Recupera um relatório de bug do dispositivo.

InputStreamSource getBugreportz ()

Recupera um bugreportz do dispositivo.

String getBuildAlias ()

Recupere o alias da compilação que o dispositivo está executando no momento.

String getBuildFlavor ()

Recupere o tipo de compilação para o dispositivo.

String getBuildId ()

Recupere a compilação que o dispositivo está executando no momento.

String getBuildSigningKeys ()

Retorna o tipo de chave usado para assinar a imagem do dispositivo

Normalmente, os dispositivos Android podem ser assinados com chaves de teste (como no AOSP) ou chaves de liberação (controladas por fabricantes de dispositivos individuais)

DeviceDescriptor getCachedDeviceDescriptor ()

Retorna um DeviceDescriptor armazenado em cache se o dispositivo estiver alocado, caso contrário, retorna o DeviceDescriptor atual.

DeviceDescriptor getCachedDeviceDescriptor (boolean shortDescriptor)

Retorna um DeviceDescriptor armazenado em cache se o dispositivo estiver alocado, caso contrário, retorna o DeviceDescriptor atual.

String[] getChildren (String path)

Alternativa para usar IFileEntry que às vezes não funciona devido a permissões.

AbstractConnection getConnection ()

A conexão atual associada ao dispositivo.

DeviceFoldableState getCurrentFoldableState ()

Retorna o estado dobrável atual do dispositivo ou nulo se alguns problemas ocorreram.

int getCurrentUser ()

Retorna o id do usuário em execução atual.

String getDeviceClass ()

Obtenha a classe do dispositivo.

long getDeviceDate ()

Retorna a data do dispositivo em milissegundos desde a época.

DeviceDescriptor getDeviceDescriptor ()

Retorne um DeviceDescriptor das informações do dispositivo para obter informações sobre ele sem passar o objeto do dispositivo real.

DeviceDescriptor getDeviceDescriptor (boolean shortDescriptor)

Retorne um DeviceDescriptor das informações do dispositivo para obter informações sobre ele sem passar o objeto do dispositivo real.

TestDeviceState getDeviceState ()

Obtenha o estado do dispositivo.

long getDeviceTimeOffset (Date date)

Helper para obter a diferença de tempo entre o dispositivo e um determinado ERROR(/Date) .

InputStreamSource getEmulatorOutput ()

Obtenha o fluxo do emulador stdout e stderr

Process getEmulatorProcess ()

Retorne o Process correspondente a este emulador.

final File getExecuteShellCommandLog ()

O log que contém todos os logs executeShellCommand(String) .

long getExternalStoreFreeSpace ()

Método auxiliar para determinar a quantidade de espaço livre no armazenamento externo do dispositivo.

String getFastbootPath ()

Retorna o caminho do binário de inicialização rápida que está sendo usado.

String getFastbootProductType ()

Método de conveniência para obter o tipo de produto deste dispositivo quando estiver no modo de inicialização rápida.

String getFastbootProductVariant ()

Método de conveniência para obter o tipo de produto deste dispositivo quando estiver no modo de inicialização rápida.

String getFastbootSerialNumber ()

Retorna o número de série do modo fastboot.

String getFastbootVariable (String variableName)

Recupere o valor da variável fastboot fornecida do dispositivo.

String getFastbootVersion ()

Retorna a string de versão do binário de inicialização rápida que está sendo usado.

IFileEntry getFileEntry (String path)

Recupere uma referência a um arquivo remoto no dispositivo.

IFileEntry getFileEntry (FileListingService.FileEntry entry)

Auxiliar não oficial para obter um FileEntry de um caminho não raiz.

getFoldableStates ()

Retorna a lista de estados dobráveis ​​no dispositivo.

IDevice getIDevice ()

Retorna uma referência ao ddmlib IDevice associado.

getInstalledPackageNames ()

Busque os nomes dos pacotes de aplicativos presentes no dispositivo.

long getIntProperty (String name, long defaultValue)

Retorna o valor inteiro da propriedade fornecida do dispositivo.

String getIpAddress ()

Obtém o endereço IP do dispositivo.

KeyguardControllerState getKeyguardState ()

Retorne um objeto para obter o estado atual do keyguard ou nulo se não for compatível.

long getLastExpectedRebootTimeMillis ()

Retorna a última vez que as APIs Tradefed dispararam uma reinicialização em milissegundos desde EPOCH conforme retornado por System.currentTimeMillis() .

int getLaunchApiLevel ()

Obtenha o primeiro nível de API lançado do dispositivo.

InputStreamSource getLogcat ()

Obtém um fluxo de instantâneo dos dados logcat.

InputStreamSource getLogcat (int maxBytes)

Obtém um fluxo instantâneo dos últimos maxBytes de dados logcat capturados.

InputStreamSource getLogcatDump ()

Obtenha um despejo do logcat atual para o dispositivo.

InputStreamSource getLogcatSince (long date)

Obtém um fluxo instantâneo de dados logcat capturados a partir da data fornecida.

String getMacAddress ()

Retorna o endereço MAC do dispositivo, nulo se falhar na consulta do dispositivo.

Integer getMainUserId ()

Retorna o id do usuário principal.

getMainlineModuleInfo ()

Obtenha as informações sobre os módulos principais instalados no dispositivo.

int getMaxNumberOfRunningUsersSupported ()

Obtenha o número máximo de usuários em execução simultânea com suporte.

int getMaxNumberOfUsersSupported ()

Obtenha o número máximo de usuários suportados.

Process getMicrodroidProcess ()
IDeviceStateMonitor getMonitor ()

Retorna o IDeviceStateMonitor associado ao dispositivo.

String getMountPoint (String mountName)

Retorna um ponto de montagem.

ITestDevice.MountPointInfo getMountPointInfo (String mountpoint)

Retorna um MountPointInfo correspondente ao caminho do ponto de montagem especificado ou null se esse caminho não tiver nada montado ou não aparecer em /proc/mounts como um ponto de montagem.

getMountPointInfo ()

Retorna uma versão analisada das informações em /proc/mounts no dispositivo

TestDeviceOptions getOptions ()

Busque as opções de teste para o dispositivo.

long getPartitionFreeSpace (String partition)

Método auxiliar para determinar a quantidade de espaço livre na partição do dispositivo.

Integer getPrimaryUserId ()

Retorna o ID do usuário primário.

ProcessInfo getProcessByName (String processName)

O método auxiliar executa o comando "pidof" e "stat" e retorna o objeto ProcessInfo com PID e hora de início do processo fornecido.

String getProcessPid (String process)

Retorna o pid do serviço ou null se algo deu errado.

String getProductType ()

Método de conveniência para obter o tipo de produto deste dispositivo.

String getProductVariant ()

Método de conveniência para obter a variante do produto deste dispositivo.

String getProperty (String name)

Recupere o valor da propriedade fornecido do dispositivo.

ITestDevice.RecoveryMode getRecoveryMode ()

Obtenha o modo de recuperação atual usado para o dispositivo.

InputStreamSource getScreenshot (String format)

Captura uma captura de tela do dispositivo.

InputStreamSource getScreenshot (long displayId)

Captura uma captura de tela do dispositivo com o ID de exibição fornecido.

InputStreamSource getScreenshot (String format, boolean rescale)

Captura uma captura de tela do dispositivo.

InputStreamSource getScreenshot ()

Captura uma captura de tela do dispositivo.

String getSerialNumber ()

Método de conveniência para obter o número de série deste dispositivo.

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

Retorna o valor da configuração solicitada.

String getSetting (String namespace, String key)

Consulte getSetting(int, String, String) e execute no usuário do sistema.

String getSimOperator ()

Retorne a operadora do cartão SIM ou nulo se não estiver disponível ou se o dispositivo não estiver disponível.

String getSimState ()

Retorna o estado do cartão SIM ou nulo se não estiver disponível ou o dispositivo não estiver disponível.

getTombstones ()

Busca e retorna a lista de lápides dos dispositivos.

long getTotalMemory ()

Retorna o tamanho total da memória física em bytes ou -1 em caso de erro interno

getUninstallablePackageNames ()

Busque os nomes dos pacotes de aplicativos que podem ser desinstalados.

boolean getUseFastbootErase ()

Obtenha se deseja usar o apagamento de inicialização rápida ou o formato de inicialização rápida para limpar uma partição no dispositivo.

int getUserFlags (int userId)

Encontre e retorne os sinalizadores de um determinado usuário.

getUserInfos ()

Obtém o mapa de useId para UserInfo no dispositivo.

int getUserSerialNumber (int userId)

Retorna o número de série associado ao userId se encontrado, -10000 nos demais casos.

IManagedTestDevice.DeviceEventResponse handleAllocationEvent (DeviceEvent event)

Processe o DeviceEvent fornecido.

Processe o DeviceEvent, que pode ou não fazer a transição deste dispositivo para um novo estado de alocação.

boolean hasFeature (String feature)

Verifique se um recurso está disponível em um dispositivo.

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

Instale um pacote Android no dispositivo.

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

Instale um pacote Android no dispositivo.

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

Instale um pacote Android no dispositivo para um determinado usuário.

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

Instale um pacote Android no dispositivo para um determinado usuário.

void invalidatePropertyCache ()
boolean isAdbRoot ()

boolean isAdbTcp ()
boolean isAppEnumerationSupported ()

Verifique se a plataforma no dispositivo oferece suporte à enumeração de aplicativos

boolean isBypassLowTargetSdkBlockSupported ()

Verifique se a plataforma no dispositivo oferece suporte para ignorar o bloqueio de alvo baixo do SDK nas instalações do aplicativo

boolean isDeviceEncrypted ()

Retorna se o dispositivo estiver criptografado.

boolean isDirectory (String path)

Retorna True se o caminho no dispositivo for um diretório, false caso contrário.

boolean isEnableAdbRoot ()
boolean isEncryptionSupported ()

Retorna se a criptografia for suportada no dispositivo.

boolean isExecutable (String fullPath)

Retorna True se o caminho do arquivo no dispositivo for um arquivo executável, caso contrário, false.

boolean isFastbootEnabled ()

Retorne se o fastboot estiver disponível para o dispositivo.

boolean isHeadless ()

Retorna true se o dispositivo for headless (sem tela), false caso contrário.

boolean isHeadlessSystemUserMode ()

Retorna se o dispositivo usa o modo de usuário do sistema headless.

boolean isMainUserPermanentAdmin ()

Retorna se o usuário principal é um administrador permanente e não pode ser excluído ou rebaixado para o status de não administrador.

boolean isMultiUserSupported ()

Determina se multiusuário é suportado.

boolean isPackageInstalled (String packageName, String userId)

Consulte o dispositivo para obter um determinado nome de pacote e um determinado ID de usuário para verificar se ele está instalado ou não para esse usuário.

boolean isPackageInstalled (String packageName)

Consulte o dispositivo para obter um determinado nome de pacote para verificar se ele está instalado ou não.

boolean isRuntimePermissionSupported ()

Verifique se a plataforma no dispositivo oferece suporte à concessão de permissão de tempo de execução

boolean isStateBootloaderOrFastbootd ()

Retorna verdadeiro se o dispositivo estiver em TestDeviceState#FASTBOOT ou TestDeviceState.FASTBOOTD .

boolean isUserRunning (int userId)

Verifique se um determinado usuário está em execução.

boolean isUserSecondary (int userId)

Retorna se o usuário especificado é um usuário secundário de acordo com seus sinalizadores.

boolean isUserVisible (int userId)

Verifica se o usuário fornecido está visível.

boolean isUserVisibleOnDisplay (int userId, int displayId)

Verifica se o usuário fornecido está visível na exibição fornecida.

boolean isVisibleBackgroundUsersOnDefaultDisplaySupported ()

Retorna se o dispositivo permite que os usuários sejam iniciados visíveis em segundo plano no ERROR(/java.android.view.Display#DEFAULT_DISPLAY) .

boolean isVisibleBackgroundUsersSupported ()

Retorna se o dispositivo permite que os usuários sejam iniciados visíveis em segundo plano.

boolean isWifiEnabled ()

Teste se o wi-fi está ativado.

listDisplayIds ()

Colete a lista de IDs de exibição disponíveis no dispositivo, conforme relatado por "Dumpsys SurfaceFlinger".

listDisplayIdsForStartingVisibleBackgroundUsers ()

Obtém a lista de exibições que podem ser usadas para start a user visible in the background .

listUsers ()

Obtém a lista de usuários no dispositivo.

boolean logAnrs ( ITestLogger logger)

Coleta e registra ANRs do dispositivo.

boolean logBugreport (String dataName, ITestLogger listener)

Método auxiliar para obter um relatório de bug e registrá-lo para os repórteres.

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

Registre uma mensagem no logcat do dispositivo.

void nonBlockingReboot ()

Emite um comando para reinicializar o dispositivo e retorna quando o comando é concluído e quando o dispositivo não está mais visível para o adb.

void postAdbRootAction ()

Substitua se o dispositivo precisar de algumas ações específicas a serem executadas após adb root e antes de o dispositivo voltar a ficar online.

void postAdbUnrootAction ()

Substitua se o dispositivo precisar de algumas ações específicas a serem executadas após o desbloqueio do adb e antes de o dispositivo voltar a ficar online.

void postBootSetup ()

Execute as instruções para configurar o dispositivo para testá-lo após cada inicialização.

void postInvocationTearDown (Throwable exception)

Etapas extras para limpeza necessária específica do dispositivo que serão executadas após a conclusão da chamada.

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

Etapas extras para configuração necessária específica do dispositivo que serão executadas no dispositivo antes do fluxo de invocação.

boolean pullDir (String deviceFilePath, File localDir)

Puxe recursivamente o conteúdo do diretório do dispositivo.

boolean pullFile (String remoteFilePath, File localFile)

Recupera um arquivo do dispositivo.

File pullFile (String remoteFilePath, int userId)

Recupera um arquivo do dispositivo, armazena-o em um ERROR(/File) temporário local e retorna esse File .

File pullFile (String remoteFilePath)

Recupera um arquivo do dispositivo, armazena-o em um ERROR(/File) temporário local e retorna esse File .

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

Recupera um arquivo do dispositivo.

String pullFileContents (String remoteFilePath)

Recupera um arquivo do dispositivo e retorna o conteúdo.

File pullFileFromExternal (String remoteFilePath)

Um método conveniente para recuperar um arquivo do armazenamento externo do dispositivo, armazená-lo em um ERROR(/File) temporário local e retornar uma referência a esse File .

boolean pushDir (File localFileDir, String deviceFilePath, excludedDirectories) pushDir (File localFileDir, String deviceFilePath, excludedDirectories)

Empurre recursivamente o conteúdo do diretório para o dispositivo enquanto exclui alguns diretórios que são filtrados.

boolean pushDir (File localFileDir, String deviceFilePath)

Empurre recursivamente o conteúdo do diretório para o dispositivo.

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

Variante de pushFile(File, String) que opcionalmente pode considerar a avaliação da necessidade do provedor de conteúdo.

boolean pushFile (File localFile, String remoteFilePath)

Empurre um arquivo para o dispositivo.

boolean pushString (String contents, String remoteFilePath)

Enviar arquivo criado a partir de uma string para o dispositivo

void reboot (String reason)

Reinicializa o dispositivo no modo adb com um determinado reason para persistir durante a reinicialização.

void reboot ()

Reinicializa o dispositivo no modo adb.

void rebootIntoBootloader ()

Reinicializa o dispositivo no modo bootloader.

void rebootIntoFastbootd ()

Reinicializa o dispositivo no modo fastbootd.

void rebootIntoRecovery ()

Reinicializa o dispositivo no modo de recuperação adb.

void rebootIntoSideload ()

Reinicializa o dispositivo no modo adb sideload (observe que este é um modo especial em recuperação)

Bloqueia até que o dispositivo entre no modo sideload

void rebootIntoSideload (boolean autoReboot)

Reinicializa o dispositivo no modo adb sideload (observe que este é um modo especial em recuperação)

Bloqueia até que o dispositivo entre no modo sideload

void rebootUntilOnline ()

Uma alternativa para reboot() que bloqueia apenas até que o dispositivo esteja online, ou seja, visível para adb.

void rebootUntilOnline (String reason)

Uma alternativa para reboot() que bloqueia apenas até que o dispositivo esteja online, ou seja, visível para adb.

void rebootUserspace ()

Reinicializa apenas a parte do espaço do usuário do dispositivo.

void rebootUserspaceUntilOnline ()

Uma alternativa para rebootUserspace() ()} que bloqueia apenas até que o dispositivo esteja online, ou seja, visível para adb.

boolean recoverDevice ()

Tenta recuperar a comunicação do dispositivo.

void registerDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver)

Registra um IDeviceActionReceiver para este dispositivo.

void remountSystemReadOnly ()

Torne a partição do sistema no dispositivo somente leitura.

void remountSystemWritable ()

Torne a partição do sistema no dispositivo gravável.

void remountVendorReadOnly ()

Torne a partição do fornecedor no dispositivo somente leitura.

void remountVendorWritable ()

Torne a partição do fornecedor no dispositivo gravável.

boolean removeAdmin (String componentName, int userId)

Remova o administrador do dispositivo fornecido em determinado usuário e retorne true se for bem-sucedido, false caso contrário.

void removeOwners ()

Remova todos os proprietários de perfil de dispositivo existentes com o melhor esforço.

boolean removeUser (int userId)

Remova um determinado usuário do dispositivo.

void resetContentProviderSetup ()

Redefina o sinalizador para configuração do provedor de conteúdo para acioná-lo novamente.

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

Método de conveniência para executar ERROR(/#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection)) com um ou mais ouvintes passados ​​como parâmetros.

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

Executa testes de instrumentação e fornece recuperação de dispositivos.

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

Igual ERROR(ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)/com.android.tradefed.device.ITestDevice#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection) ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)) mas executa o teste para determinado usuário.

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

O mesmo que ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, ITestLifeCycleReceiver...) mas executa o teste para um determinado usuário.

void setConfiguration ( IConfiguration configuration)

Injeta o IConfiguration em uso.

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

Define a data no dispositivo

Nota: definir a data no dispositivo requer root

boolean setDeviceOwner (String componentName, int userId)

Defina um componente de administração do dispositivo como proprietário do dispositivo em determinado usuário.

void setDeviceState ( TestDeviceState deviceState)

Atualize o estado do dispositivo.

void setEmulatorOutputStream ( SizeLimitedOutputStream output)

Para o emulador, defina SizeLimitedOutputStream para registrar a saída

void setEmulatorProcess (Process p)

Define o Process , quando este dispositivo é um emulador.

void setFastbootEnabled (boolean fastbootEnabled)

Defina a opção de inicialização rápida para o dispositivo.

void setFastbootPath (String fastbootPath)

Define o caminho para o binário de inicialização rápida que deve ser usado.

void setIDevice (IDevice newDevice)

Atualize o IDevice associado a este ITestDevice.

void setLogStartDelay (int delay)

Define o tempo em ms de espera antes de iniciar a captura do logcat para um dispositivo online.

void setOptions ( TestDeviceOptions options)

Defina TestDeviceOptions para o dispositivo

boolean setProperty (String propKey, String propValue)

Define o valor da propriedade fornecido no dispositivo.

void setRecovery ( IDeviceRecovery recovery)

Defina o IDeviceRecovery a ser usado para este dispositivo.

void setRecoveryMode ( ITestDevice.RecoveryMode mode)

Defina o modo de recuperação atual a ser usado para o dispositivo.

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

Consulte setSetting(int, String, String, String) e executado no usuário do sistema.

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

Adicione um valor de configuração ao namespace de um determinado usuário.

void setTestLogger ( ITestLogger testLogger)

Injeta a instância ITestLogger

void setUseFastbootErase (boolean useFastbootErase)

Defina se deseja usar o apagamento de inicialização rápida ou o formato de inicialização rápida para limpar uma partição no dispositivo.

void startLogcat ()

Comece a capturar a saída logcat do dispositivo em segundo plano.

boolean startUser (int userId)

Inicia um determinado usuário em segundo plano se estiver parado no momento.

boolean startUser (int userId, boolean waitFlag)

Inicia um determinado usuário em segundo plano se estiver parado no momento.

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

Inicia um determinado usuário em segundo plano, visível na exibição fornecida (ou seja, permitindo que o usuário inicie atividades nessa exibição).

void stopEmulatorOutput ()

Feche e exclua a saída do emulador.

void stopLogcat ()

Pare de capturar a saída do logcat do dispositivo e descarte os dados do logcat salvos no momento.

boolean stopUser (int userId)

Interrompe um determinado usuário.

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

Pare um determinado usuário.

String switchToAdbTcp ()

Mude o dispositivo para o modo adb-over-tcp.

boolean switchToAdbUsb ()

Mude o dispositivo para o modo adb sobre usb.

boolean switchUser (int userId)

Mude para outro userId com um tempo limite padrão.

boolean switchUser (int userId, long timeout)

Alterne para outro userId com o tempo limite fornecido como prazo.

boolean syncFiles (File localFileDir, String deviceFilePath)

Sincroniza incrementalmente o conteúdo de um diretório de arquivo local com o dispositivo.

Bugreport takeBugreport ()

Pegue um relatório de bug e o retorne dentro de um objeto Bugreport para tratá-lo.

String uninstallPackage (String packageName)

Desinstale um pacote Android do dispositivo.

String uninstallPackageForUser (String packageName, int userId)

Desinstale um pacote Android do dispositivo para um determinado usuário.

boolean unlockDevice ()

Desbloqueia o dispositivo se ele estiver em um estado criptografado.

boolean waitForBootComplete (long timeOut)

Bloqueia até que o sinalizador de inicialização completa do dispositivo seja definido.

boolean waitForDeviceAvailable ()

Aguarda até que o dispositivo seja responsivo e esteja disponível para teste.

boolean waitForDeviceAvailable (long waitTime)

Aguarda até que o dispositivo seja responsivo e esteja disponível para teste.

boolean waitForDeviceAvailableInRecoverPath (long waitTime)

Aguarda até que o dispositivo esteja responsivo e disponível sem considerar o caminho de recuperação.

void waitForDeviceBootloader ()

Bloqueia até que o dispositivo fique visível via fastboot.

boolean waitForDeviceInRecovery (long waitTime)

Blocos para o dispositivo estar no estado 'adb recovery' (observe que isso é diferente de IDeviceRecovery ).

boolean waitForDeviceInSideload (long waitTime)

Blocos para o dispositivo estar no estado 'adb sideload'

boolean waitForDeviceNotAvailable (long waitTime)

Blocos para o dispositivo não estarem disponíveis, ou seja, ausentes do adb

void waitForDeviceOnline ()

Bloqueia até que o dispositivo fique visível via adb.

void waitForDeviceOnline (long waitTime)

Bloqueia até que o dispositivo fique visível via adb.

boolean waitForDeviceShell (long waitTime)

Aguarda que o dispositivo responda a um comando shell adb básico.

Métodos protegidos

void addExtraConnectionBuilderArgs ( DefaultConnection.ConnectionBuilder builder)
String[] buildAdbShellCommand (String command, boolean forceExitStatusDetection)

Constrói o comando do sistema operacional para a sessão de comando adb shell fornecida e args

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

Crie um RebootDeviceAction para ser usado ao executar uma ação de reinicialização.

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

Execute uma reinicialização adb.

void ensureRuntimePermissionSupported ()

método auxiliar para lançar exceção se a permissão de tempo de execução não for suportada

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

Obtenha a instância RunUtil para usar.

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

Busque uma propriedade de dispositivo, do cache ddmlib por padrão, e volte para `adb shell getprop` ou `fastboot getvar` dependendo se o dispositivo está em Fastboot ou não.

boolean isInRebootCallback ()

Retorna se os callbacks de reinicialização estão sendo executados no momento ou não.

boolean isNewer (File localFile, IFileEntry entry)

Retorna true se o arquivo local for mais recente que o arquivo remoto.

void notifyRebootEnded ()

Notifica todos IDeviceActionReceiver sobre o evento de término da reinicialização.

void notifyRebootStarted ()

Notifica todos IDeviceActionReceiver sobre o evento de início da reinicialização.

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

Executa uma ação neste dispositivo.

void postAdbReboot ()

Possíveis ações extras que podem ser executadas após uma reinicialização.

void prePostBootSetup ()

Permite que cada tipo de dispositivo (AndroidNativeDevice, TestDevice) substitua esse método para configuração específica de pós-inicialização.

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

Defina a instância Clock a ser usada.

void setMicrodroidProcess (Process process)

Marca o TestDevice como microdroid e define seu CID.

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

Executa um comando fastboot simples com variáveis ​​de ambiente e relata o status do comando.

CommandResult simpleFastbootCommand (long timeout, String[] fullCmd)

Executa um comando fastboot simples e relata o status do comando.

boolean waitForDeviceNotAvailable (String operationDesc, long time)

Aguarde para ver o dispositivo ficar indisponível (pare de relatar ao adb).

Constantes

INVALID_USER_ID

public static final int INVALID_USER_ID

Valor retornado para qualquer id de usuário inválido/não encontrado: UserHandle definiu o valor -10000

Valor constante: -10000 (0xffffd8f0)

MAX_HOST_DEVICE_TIME_OFFSET

protected static final long MAX_HOST_DEVICE_TIME_OFFSET

Valor constante: 5000 (0x0000000000001388)

MAX_RETRY_ATTEMPTS

protected static final int MAX_RETRY_ATTEMPTS

o número padrão de tentativas de repetição de comando para executar

Valor constante: 2 (0x00000002)

Campos

CARTÃO SD

protected static final String SD_CARD

STORAGE_EMULATED

protected static final String STORAGE_EMULATED

mOpções

protected TestDeviceOptions mOptions

mStateMonitor

protected final IDeviceStateMonitor mStateMonitor

Construtores públicos

Dispositivo nativo

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

Cria um TestDevice .

Parâmetros
device IDevice : o IDevice associado

stateMonitor IDeviceStateMonitor : o mecanismo IDeviceStateMonitor a ser usado

allocationMonitor IDeviceMonitor : o IDeviceMonitor para informar sobre as mudanças de estado de alocação. pode ser nulo

Métodos públicos

batchPrefetchStartupBuildProps

public void batchPrefetchStartupBuildProps ()

Micro otimização (cerca de 400 millis) pré-buscando todos os props que precisamos, em vez de chamar 'adb getprop' para cada um. ou seja, é tão rápido buscar todas as propriedades quanto buscar uma. Coisas como device.getApiLevel(), checkApiLevelAgainstNextRelease e getBuildAlias ​​chamam `adb getprop` sob o capô. Nós os buscamos em uma chamada e chamamos NativeDevice.setProperty. Mesmo se não fizermos isso, o próprio NativeDevice chamará setProperty e armazenará em cache o resultado para chamadas futuras. Estamos apenas fazendo isso um pouco mais cedo. Se o dispositivo estiver em recuperação ou houver outros erros ao buscar os props, simplesmente os ignoramos.

canSwitchToHeadlessSystemUser

public boolean canSwitchToHeadlessSystemUser ()

Retorna se é permitido alternar para o usuário headless SYSTEM.

devoluções
boolean

lances
DeviceNotAvailableException

checkApiLevelAgainstNextRelease

public boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

Verifique se um recurso é ou não suportado no momento, dado um nível minimamente suportado. Este método leva em consideração recursos ainda não lançados, antes que o nível da API seja elevado.

Parâmetros
strictMinLevel int : O nível mínimo possível estrito que suporta o recurso.

devoluções
boolean Verdadeiro se o nível for compatível. Falso caso contrário.

lances
DeviceNotAvailableException

verificarConectividade

public boolean checkConnectivity ()

Verifique se o dispositivo tem conectividade de rede.

devoluções
boolean true se o dispositivo tiver uma conexão de rede funcionando, false overwise.

lances
DeviceNotAvailableException

clearErrorDialogs

public boolean clearErrorDialogs ()

Tente descartar todas as caixas de diálogo de erro atualmente exibidas na interface do usuário do dispositivo.

devoluções
boolean true se nenhuma caixa de diálogo estiver presente ou se as caixas de diálogo forem limpas com êxito. false caso contrário.

lances
DeviceNotAvailableException

clearLastConnectedWifiNetwork

public void clearLastConnectedWifiNetwork ()

Limpa a última rede wi-fi conectada. Isso deve ser chamado ao iniciar uma nova chamada para evitar a conexão com a rede wi-fi usada no teste anterior após a reinicialização do dispositivo.

clearLogcat

public void clearLogcat ()

Exclui todos os dados logcat acumulados.

Isso é útil para casos em que você deseja garantir ITestDevice#getLogcat() retorne apenas dados de log produzidos após um determinado ponto (como após o flash de uma nova compilação de dispositivo etc.).

connectToWifiNetwork

public boolean connectToWifiNetwork ( wifiSsidToPsk, 
                boolean scanSsid)

Conecta-se a uma rede wi-fi.

Ativa o wifi e bloqueia até que uma conexão bem-sucedida seja feita com uma das redes wifi fornecidas no mapa wifiSsidToPsk. Depois que uma conexão é estabelecida, a instância tentará restaurá-la após cada reinicialização até que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() seja chamado.

Parâmetros
wifiSsidToPsk : Um mapa de SSIDs wi-fi para senhas.

scanSsid boolean : se deve procurar por SSIDs ocultos para esta rede.

devoluções
boolean true se conectado à rede wi-fi com sucesso. false caso contrário

lances
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork (String wifiSsid, 
                String wifiPsk)

Conecta-se a uma rede wi-fi.

Liga o wi-fi e bloqueia até que uma conexão bem-sucedida seja feita com a rede wi-fi especificada. Depois que uma conexão é estabelecida, a instância tentará restaurá-la após cada reinicialização até que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() seja chamado.

Parâmetros
wifiSsid String : o ssid wi-fi para se conectar

wifiPsk String : Senha PSK ou nula se não criptografada

devoluções
boolean true se conectado à rede wi-fi com sucesso. false caso contrário

lances
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork ( wifiSsidToPsk)

Conecta-se a uma rede wi-fi.

Ativa o wifi e bloqueia até que uma conexão bem-sucedida seja feita com uma das redes wifi fornecidas no mapa wifiSsidToPsk. Depois que uma conexão é estabelecida, a instância tentará restaurá-la após cada reinicialização até que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() seja chamado.f

Parâmetros
wifiSsidToPsk : Um mapa de SSIDs wi-fi para senhas.

devoluções
boolean true se conectado à rede wi-fi com sucesso. false caso contrário

lances
DeviceNotAvailableException

connectToWifiNetwork

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

Conecta-se a uma rede wi-fi.

Liga o wi-fi e bloqueia até que uma conexão bem-sucedida seja feita com a rede wi-fi especificada. Depois que uma conexão é estabelecida, a instância tentará restaurá-la após cada reinicialização até que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() seja chamado.

Parâmetros
wifiSsid String : o ssid wi-fi para se conectar

wifiPsk String : Senha PSK ou nula se não criptografada

scanSsid boolean : se deve procurar SSID oculto para esta rede.

devoluções
boolean true se conectado à rede wi-fi com sucesso. false caso contrário

lances
DeviceNotAvailableException

connectToWifiNetworkIfNeeded

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

Uma variante de connectToWifiNetwork(String, String) que só conecta se o dispositivo não tiver conectividade de rede no momento.

Parâmetros
scanSsid boolean : se deve procurar SSID oculto para esta rede

devoluções
boolean true se conectado à rede wi-fi com sucesso. false caso contrário

lances
DeviceNotAvailableException

connectToWifiNetworkIfNeeded

public boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk)

Uma variante de connectToWifiNetwork(String, String) que só conecta se o dispositivo não tiver conectividade de rede no momento.

devoluções
boolean true se conectado à rede wi-fi com sucesso. false caso contrário

lances
DeviceNotAvailableException

criarusuário

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

Crie um usuário com um determinado nome e os sinalizadores fornecidos

Parâmetros
name String : do usuário a ser criado no dispositivo

guest boolean : habilite o sinalizador de usuário --guest durante a criação

ephemeral boolean : habilite o sinalizador de usuário --ephemeral durante a criação

devoluções
int id do usuário criado

lances
DeviceNotAvailableException

criarusuário

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

Crie um usuário com um determinado nome e os sinalizadores fornecidos

Parâmetros
name String : do usuário a ser criado no dispositivo

guest boolean : habilite o sinalizador de usuário --guest durante a criação

ephemeral boolean : habilite o sinalizador de usuário --ephemeral durante a criação

forTesting boolean : habilite o sinalizador de teste --for-testing durante a criação

devoluções
int id do usuário criado

lances
DeviceNotAvailableException

criarusuário

public int createUser (String name)

Crie um usuário com um determinado nome e sinalizadores padrão 0.

Parâmetros
name String : do usuário a ser criado no dispositivo

devoluções
int o número inteiro para o ID do usuário criado

lances
DeviceNotAvailableException

createUserNoThrow

public int createUserNoThrow (String name)

Crie um usuário com um determinado nome e sinalizadores padrão 0.

Parâmetros
name String : do usuário a ser criado no dispositivo

devoluções
int o número inteiro para o ID do usuário criado ou -1 para erro.

lances
DeviceNotAvailableException

deletarArquivo

public void deleteFile (String deviceFilePath)

Método auxiliar para excluir um arquivo ou diretório no dispositivo.

Parâmetros
deviceFilePath String : o caminho absoluto do arquivo no dispositivo.

lances
DeviceNotAvailableException

deregisterDeviceActionReceiver

public void deregisterDeviceActionReceiver (IDeviceActionReceiver deviceActionReceiver)

Remove o IDeviceActionReceiver registrado.

Parâmetros
deviceActionReceiver IDeviceActionReceiver : um IDeviceActionReceiver que será removido.

dispositivoSoftRestarted

public boolean deviceSoftRestarted (ProcessInfo prevSystemServerProcess)

Método auxiliar para verificar se o dispositivo reiniciou por software comparando o system_server atual com o system_server anterior ProcessInfo . Use getProcessByName(String) para obter ProcessInfo .

Parâmetros
prevSystemServerProcess ProcessInfo : o processo system_server anterior ProcessInfo .

devoluções
boolean true se o dispositivo for reiniciado por software

lances
DeviceNotAvailableException

deviceSoftRestartedSince

public boolean deviceSoftRestartedSince (long utcEpochTime, 
                TimeUnit timeUnit)

Método auxiliar para verificar se o dispositivo reiniciou por software desde a hora UTC desde a época do dispositivo e seu ERROR(/TimeUnit) . Soft-Restart refere-se a system_server reiniciado fora de uma reinicialização forçada do dispositivo (por exemplo: reinicialização solicitada). O dispositivo atual utcEpochTime em Millisecond pode ser obtido pelo método getDeviceDate() .

Parâmetros
utcEpochTime long : o tempo do dispositivo em segundos desde a época.

timeUnit TimeUnit : a unidade de tempo TimeUnit para o utcEpochTime fornecido.

devoluções
boolean true se o dispositivo for reiniciado por software

lances
DeviceNotAvailableException

disableAdbRoot

public boolean disableAdbRoot ()

Desativa o adb root.

Desativar adb root pode fazer com que o dispositivo se desconecte do adb. Este método será bloqueado até que o dispositivo esteja disponível.

devoluções
boolean true se for bem-sucedido.

lances
DeviceNotAvailableException

desativarKeyguard

public void disableKeyguard ()

Tenta desativar a proteção do teclado.

Primeiro, espere que o envio de entrada fique pronto, isso acontece ao mesmo tempo em que o dispositivo relata BOOT_COMPLETE, aparentemente de forma assíncrona, porque a implementação atual da estrutura tem uma condição de corrida ocasional. Em seguida, o comando é enviado para descartar o keyguard (funciona apenas em não-seguros)

lances
DeviceNotAvailableException

desativarNetworkMonitor

public boolean disableNetworkMonitor ()

Desativa o monitoramento de rede no dispositivo.

devoluções
boolean true se o monitoramento for desabilitado com sucesso. false se falhou.

lances
DeviceNotAvailableException

desconectarDeWifi

public boolean disconnectFromWifi ()

Desconecta de uma rede wi-fi.

Remove todas as redes da lista de redes conhecidas e desativa o wifi.

devoluções
boolean true se desconectado da rede wi-fi com sucesso. false se a desconexão falhou.

lances
DeviceNotAvailableException

doesFileExist

public boolean doesFileExist (String deviceFilePath, 
                int userId)

Método auxiliar para determinar se o arquivo no dispositivo existe para um determinado usuário.

Parâmetros
deviceFilePath String : o caminho absoluto do arquivo no dispositivo a ser verificado

userId int : O ID do usuário contra o qual verificar a existência do arquivo

devoluções
boolean true se o arquivo existir, false caso contrário.

lances
DeviceNotAvailableException

doesFileExist

public boolean doesFileExist (String deviceFilePath)

Método auxiliar para determinar se o arquivo no dispositivo existe.

Parâmetros
deviceFilePath String : o caminho absoluto do arquivo no dispositivo a ser verificado

devoluções
boolean true se o arquivo existir, false caso contrário.

lances
DeviceNotAvailableException

dumpHeap

public File dumpHeap (String process, 
                String devicePath)

Tente despejar o heap do system_server. É responsabilidade do chamador limpar o arquivo despejado.

Parâmetros
process String : o nome do processo do dispositivo para despejar.

devicePath String : o caminho no dispositivo onde colocar o dump. Este deve ser um local onde as permissões permitem.

devoluções
File o ERROR(/File) contendo o relatório. Nulo se algo falhou.

lances
DeviceNotAvailableException

enableAdbRoot

public boolean enableAdbRoot ()

Ativa adb root. Se a configuração "enable-root" for "false", registrará uma mensagem e retornará sem habilitar o root.

Habilitar adb root pode fazer com que o dispositivo se desconecte do adb. Este método será bloqueado até que o dispositivo esteja disponível.

devoluções
boolean true se for bem-sucedido.

lances
DeviceNotAvailableException

enableNetworkMonitor

public boolean enableNetworkMonitor ()

Ativa o monitoramento de rede no dispositivo.

devoluções
boolean true se o monitoramento for ativado com êxito. false se falhou.

lances
DeviceNotAvailableException

executeAdbCommand

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

Método auxiliar que executa um comando adb como um comando do sistema com um tempo limite especificado.

executeShellCommand(String) deve ser usado sempre que possível, pois esse método fornece melhor detecção de falha e desempenho.

Parâmetros
timeout long : o tempo em milissegundos antes que o dispositivo seja considerado sem resposta, 0L para nenhum tempo limite

cmdArgs String : o comando adb e os argumentos a serem executados

devoluções
String o stdout do comando. null se o comando falhou ao executar.

lances
DeviceNotAvailableException

executeAdbCommand

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

Método auxiliar que executa um comando adb como um comando do sistema com um tempo limite especificado.

executeShellCommand(String) deve ser usado sempre que possível, pois esse método fornece melhor detecção de falha e desempenho.

Parâmetros
timeout long : o tempo em milissegundos antes que o dispositivo seja considerado sem resposta, 0L para nenhum tempo limite

envMap : ambiente a definir para o comando

cmdArgs String : o comando adb e os argumentos a serem executados

devoluções
String o stdout do comando. null se o comando falhou ao executar.

lances
DeviceNotAvailableException

executeAdbCommand

public String executeAdbCommand (String... cmdArgs)

Método auxiliar que executa um comando adb como um comando do sistema.

executeShellCommand(String) deve ser usado sempre que possível, pois esse método fornece melhor detecção de falha e desempenho.

Parâmetros
cmdArgs String : o comando adb e os argumentos a serem executados

devoluções
String o stdout do comando. null se o comando falhou ao executar.

lances
DeviceNotAvailableException

executeFastbootCommand

public CommandResult executeFastbootCommand (String... cmdArgs)

Método auxiliar que executa um comando fastboot como um comando do sistema com um tempo limite padrão de 2 minutos.

Espera-se que seja usado quando o dispositivo já estiver no modo de inicialização rápida.

Parâmetros
cmdArgs String : o comando fastboot e os argumentos a serem executados

devoluções
CommandResult o CommandResult contendo a saída do comando

lances
DeviceNotAvailableException

executeFastbootCommand

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

Método auxiliar que executa um comando fastboot como um comando do sistema.

Espera-se que seja usado quando o dispositivo já estiver no modo de inicialização rápida.

Parâmetros
timeout long : o tempo em milissegundos antes do comando expirar

cmdArgs String : o comando fastboot e os argumentos a serem executados

devoluções
CommandResult o CommandResult contendo a saída do comando

lances
DeviceNotAvailableException

executeLongFastbootCommand

public CommandResult executeLongFastbootCommand (String... cmdArgs)

Método auxiliar que executa um comando fastboot de longa duração como um comando do sistema.

Idêntico a executeFastbootCommand(String) exceto que usa um tempo limite maior.

Parâmetros
cmdArgs String : the fastboot command and arguments to run

devoluções
CommandResult the CommandResult containing output of command

lances
DeviceNotAvailableException

executeLongFastbootCommand

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

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

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

Parâmetros
envVarMap : the system environment variables that the fastboot command run with

cmdArgs String : the fastboot command and arguments to run

devoluções
CommandResult the CommandResult containing output of command

lances
DeviceNotAvailableException

executeShellCommand

public String executeShellCommand (String command)

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

Parâmetros
command String : the adb shell command to run

devoluções
String the shell output

lances
DeviceNotAvailableException

executeShellCommand

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

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

Parâmetros
command String : the adb shell command to run

receiver IShellOutputReceiver : the IShellOutputReceiver to direct shell output to.

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

timeUnit TimeUnit : unit for maxTimeToOutputShellResponse

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

lances
DeviceNotAvailableException

executeShellCommand

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

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

Parâmetros
command String : the adb shell command to run

receiver IShellOutputReceiver : the IShellOutputReceiver to direct shell output to.

maxTimeoutForCommand long : the maximum timeout for the command to complete; unit as specified in timeUnit

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

timeUnit TimeUnit : unit for maxTimeToOutputShellResponse

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

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

Parâmetros
command String : the adb shell command to run

receiver IShellOutputReceiver : the IShellOutputReceiver to direct shell output to.

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

Parâmetros
cmd String : The command that should be run.

devoluções
CommandResult The result in CommandResult .

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

Parâmetros
cmd String : The command that should be run.

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

devoluções
CommandResult The result in CommandResult .

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

Parâmetros
cmd String : The command that should be run.

pipeAsInput File : A ERROR(/File) that will be piped as input to the command, or null.

devoluções
CommandResult The result in CommandResult .

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

Parâmetros
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.

devoluções
CommandResult

lances
DeviceNotAvailableException

executeShellV2Command

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

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

Parâmetros
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

devoluções
CommandResult

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

Parâmetros
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.

devoluções
CommandResult

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

Parâmetros
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.

devoluções
CommandResult

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

Parâmetros
partition String : the partition to wipe

devoluções
CommandResult the CommandResult containing output of command

lances
DeviceNotAvailableException

getActiveApexes

public  getActiveApexes ()

Fetch the information about APEXes activated on the device.

devoluções
ERROR(/Set) of ApexInfo currently activated on the device

lances
DeviceNotAvailableException

getAllSettings

public  getAllSettings (String namespace)

Return key value pairs of requested namespace.

Parâmetros
namespace String : must be one of {"system", "secure", "global"}

devoluções
the map of key value pairs. Null if namespace is not supported.

lances
DeviceNotAvailableException

getAllocationState

public DeviceAllocationState getAllocationState ()

Return the current allocation state of device

devoluções
DeviceAllocationState

getAndroidId

public String getAndroidId (int userId)

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

Parâmetros
userId int

devoluções
String

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

devoluções
Map of android ids found matching user ids.

lances
DeviceNotAvailableException

getApiLevel

public int getApiLevel ()

Get the device API Level. Defaults to UNKNOWN_API_LEVEL .

devoluções
int an integer indicating the API Level of device

lances
DeviceNotAvailableException

getAppPackageInfo

public PackageInfo getAppPackageInfo (String packageName)

Fetch information about a package installed on device.

Parâmetros
packageName String

devoluções
PackageInfo the PackageInfo or null if information could not be retrieved

lances
DeviceNotAvailableException

getAppPackageInfos

public  getAppPackageInfos ()

Fetch information of packages installed on the device.

devoluções
ERROR(/List) of PackageInfo s installed on the device.

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

devoluções
String the String baseband version or null if it cannot be determined (device has no radio or version string cannot be read)

lances
DeviceNotAvailableException

getBattery

public Integer getBattery ()

Returns the current battery level of a device or Null if battery level unavailable.

devoluções
Integer

getBooleanProperty

public boolean getBooleanProperty (String name, 
                boolean defaultValue)

Returns boolean value of the given property.

Parâmetros
name String : the property name

defaultValue boolean : default value to return if property is empty or doesn't exist.

devoluções
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.

lances
DeviceNotAvailableException

getBootHistory

public  getBootHistory ()

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

devoluções
Map of boot time (UTC time in second since Epoch) and boot reason

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

Parâmetros
utcEpochTime long : the device time since Epoch.

timeUnit TimeUnit : the time unit TimeUnit .

devoluções
Map of boot time (UTC time in second since Epoch) and boot reason

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

devoluções
String the String bootloader version or null if it cannot be found

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

devoluções
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

devoluções
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

devoluções
String the build alias or fall back to build id if it could not be retrieved

lances
DeviceNotAvailableException

getBuildFlavor

public String getBuildFlavor ()

Retrieve the build flavor for the device.

devoluções
String the build flavor or null if it could not be retrieved

lances
DeviceNotAvailableException

getBuildId

public String getBuildId ()

Retrieve the build the device is currently running.

devoluções
String the build id or IBuildInfo#UNKNOWN_BUILD_ID if it could not be retrieved

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

devoluções
String The signing key if found, null otherwise.

lances
DeviceNotAvailableException

getCachedDeviceDescriptor

public DeviceDescriptor getCachedDeviceDescriptor ()

Returns a cached DeviceDescriptor if the device is allocated, otherwise returns the current DeviceDescriptor .

devoluções
DeviceDescriptor

getCachedDeviceDescriptor

public DeviceDescriptor getCachedDeviceDescriptor (boolean shortDescriptor)

Returns a cached DeviceDescriptor if the device is allocated, otherwise returns the current DeviceDescriptor .

Parâmetros
shortDescriptor boolean : Whether or not to limit descriptor to bare minimum info

devoluções
DeviceDescriptor

getChildren

public String[] getChildren (String path)

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

Parâmetros
path String : is the path on the device where to do the search

devoluções
String[] Array of string containing all the file in a path on the device.

lances
DeviceNotAvailableException

getConnection

public AbstractConnection getConnection ()

The current connection associated with the device.

devoluções
AbstractConnection

getCurrentFoldableState

public DeviceFoldableState getCurrentFoldableState ()

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

devoluções
DeviceFoldableState

lances
DeviceNotAvailableException

getCurrentUser

public int getCurrentUser ()

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

devoluções
int

lances
DeviceNotAvailableException

getDeviceClass

public String getDeviceClass ()

Get the device class.

devoluções
String the String device class.

getDeviceDate

public long getDeviceDate ()

Return the date of the device in millisecond since epoch.

devoluções
long the date of the device in epoch format.

lances
DeviceNotAvailableException

getDeviceDescriptor

public DeviceDescriptor getDeviceDescriptor ()

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

devoluções
DeviceDescriptor

getDeviceDescriptor

public DeviceDescriptor getDeviceDescriptor (boolean shortDescriptor)

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

Parâmetros
shortDescriptor boolean : Whether or not to limit descriptor to bare minimum info

devoluções
DeviceDescriptor

getDeviceState

public TestDeviceState getDeviceState ()

Get the device's state.

devoluções
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.

Parâmetros
date Date

devoluções
long the difference in milliseconds

lances
DeviceNotAvailableException

getEmulatorOutput

public InputStreamSource getEmulatorOutput ()

Get the stream of emulator stdout and stderr

devoluções
InputStreamSource emulator output

getEmulatorProcess

public Process getEmulatorProcess ()

Return the Process corresponding to this emulator.

devoluções
Process the Process or null

getExecuteShellCommandLog

public final File getExecuteShellCommandLog ()

The log that contains all the executeShellCommand(String) logs.

devoluções
File

getExternalStoreFreeSpace

public long getExternalStoreFreeSpace ()

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

devoluções
long the amount of free space in KB

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

devoluções
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.

devoluções
String the String product type name or null if it cannot be determined

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

devoluções
String the String product type name or null if it cannot be determined

lances
DeviceNotAvailableException

getFastbootSerialNumber

public String getFastbootSerialNumber ()

Returns the fastboot mode serial number.

devoluções
String

getFastbootVariable

public String getFastbootVariable (String variableName)

Retrieve the given fastboot variable value from the device.

Parâmetros
variableName String : the variable name

devoluções
String the property value or null if it does not exist

lances
DeviceNotAvailableException

getFastbootVersion

public String getFastbootVersion ()

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

devoluções
String

getFileEntry

public IFileEntry getFileEntry (String path)

Retrieve a reference to a remote file on device.

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

devoluções
IFileEntry the IFileEntry or null if file at given path cannot be found

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

Parâmetros
entry FileListingService.FileEntry : a FileEntry not necessarily root as Ddmlib requires.

devoluções
IFileEntry a FileEntryWrapper representing the FileEntry.

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

devoluções

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

devoluções
IDevice the IDevice

getInstalledPackageNames

public  getInstalledPackageNames ()

Fetch the application package names present on the device.

devoluções
ERROR(/Set) of String package names currently installed on the device.

lances
DeviceNotAvailableException

getIntProperty

public long getIntProperty (String name, 
                long defaultValue)

Returns integer value of the given property from the device.

Parâmetros
name String : the property name

defaultValue long : default value to return if property is empty or doesn't exist.

devoluções
long the property value or defaultValue if the property is empty, doesn't exist, or doesn't have an integer value.

lances
DeviceNotAvailableException

getIpAddress

public String getIpAddress ()

Gets the device's IP address.

devoluções
String the device's IP address, or null if device has no IP address

lances
DeviceNotAvailableException

getKeyguardState

public KeyguardControllerState getKeyguardState ()

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

devoluções
KeyguardControllerState a KeyguardControllerState containing a snapshot of the state of the keyguard and returns Null if the Keyguard query is not supported.

lances
DeviceNotAvailableException

getLastExpectedRebootTimeMillis

public long getLastExpectedRebootTimeMillis ()

Returns the last time Tradefed APIs triggered a reboot in milliseconds since EPOCH as returned by System.currentTimeMillis() .

devoluções
long

getLaunchApiLevel

public int getLaunchApiLevel ()

Get the device's first launched API Level. Defaults to UNKNOWN_API_LEVEL .

devoluções
int an integer indicating the first launched API Level of device

lances
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

    devoluções
    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.

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

    devoluções
    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.

    devoluções
    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() .

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

    devoluções
    InputStreamSource

    getMacAddress

    public String getMacAddress ()

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

    devoluções
    String

    getMainUserId

    public Integer getMainUserId ()

    Returns the main user id.

    devoluções
    Integer the userId of the main user if there is one, and null if there is no main user.

    lances
    DeviceNotAvailableException

    getMainlineModuleInfo

    public  getMainlineModuleInfo ()

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

    devoluções
    ERROR(/Set) of String mainline modules currently installed on the device.

    lances
    DeviceNotAvailableException

    getMaxNumberOfRunningUsersSupported

    public int getMaxNumberOfRunningUsersSupported ()

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

    devoluções
    int an integer indicating the number of simultaneously running users

    lances
    DeviceNotAvailableException

    getMaxNumberOfUsersSupported

    public int getMaxNumberOfUsersSupported ()

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

    devoluções
    int an integer indicating the number of supported users

    lances
    DeviceNotAvailableException

    getMicrodroidProcess

    public Process getMicrodroidProcess ()

    devoluções
    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.

    devoluções
    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)

    Parâmetros
    mountName String : the name of the mount point

    devoluções
    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.

    Parâmetros
    mountpoint String

    devoluções
    ITestDevice.MountPointInfo A ERROR(/List) of MountPointInfo containing the information in "/proc/mounts"

    lances
    DeviceNotAvailableException

    getMountPointInfo

    public  getMountPointInfo ()

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

    devoluções
    A ERROR(/List) of MountPointInfo containing the information in "/proc/mounts"

    lances
    DeviceNotAvailableException

    getOptions

    public TestDeviceOptions getOptions ()

    Fetch the test options for the device.

    devoluções
    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.

    Parâmetros
    partition String

    devoluções
    long the amount of free space in KB

    lances
    DeviceNotAvailableException

    getPrimaryUserId

    public Integer getPrimaryUserId ()

    Returns the primary user id.

    devoluções
    Integer the userId of the primary user if there is one, and null if there is no primary user.

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

    Parâmetros
    processName String : the proces name String.

    devoluções
    ProcessInfo ProcessInfo of given processName

    lances
    DeviceNotAvailableException

    getProcessPid

    public String getProcessPid (String process)

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

    Parâmetros
    process String : The proces name String.

    devoluções
    String

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

    devoluções
    String the String product type name. Will not be null

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

    devoluções
    String the String product variant name or null if it cannot be determined

    lances
    DeviceNotAvailableException

    getProperty

    public String getProperty (String name)

    Retrieve the given property value from the device.

    Parâmetros
    name String : the property name

    devoluções
    String the property value or null if it does not exist

    lances
    DeviceNotAvailableException

    getRecoveryMode

    public ITestDevice.RecoveryMode getRecoveryMode ()

    Get the current recovery mode used for the device.

    devoluções
    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

    Parâmetros
    format String : supported PNG, JPEG

    devoluções
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    lances
    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'

    Parâmetros
    displayId long : the display id of the screen to get screenshot from.

    devoluções
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

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

    Parâmetros
    format String : supported PNG, JPEG

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

    devoluções
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    lances
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot ()

    Grabs a screenshot from the device.

    devoluções
    InputStreamSource a InputStreamSource of the screenshot in png format, or null if the screenshot was not successful.

    lances
    DeviceNotAvailableException

    getSerialNumber

    public String getSerialNumber ()

    Convenience method to get serial number of this device.

    devoluções
    String the String serial number

    getSetting

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

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

    Parâmetros
    userId int

    namespace String

    key String

    devoluções
    String the value associated with the namespace:key of a user. Null if not found.

    lances
    DeviceNotAvailableException

    getSetting

    public String getSetting (String namespace, 
                    String key)

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

    Parâmetros
    namespace String

    key String

    devoluções
    String

    lances
    DeviceNotAvailableException

    getSimOperator

    public String getSimOperator ()

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

    devoluções
    String

    getSimState

    public String getSimState ()

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

    devoluções
    String

    getTombstones

    public  getTombstones ()

    Fetch and return the list of tombstones from the devices. Requires root.

    method is best-effort so if one tombstone fails to be pulled for any reason it will be missing from the list. Only a DeviceNotAvailableException will terminate the method early.

    devoluções
    A list of tombstone files, empty if no tombstone.

    lances
    DeviceNotAvailableException

    getTotalMemory

    public long getTotalMemory ()

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

    devoluções
    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.

    devoluções
    ERROR(/Set) of uninstallable String package names currently installed on the device.

    lances
    DeviceNotAvailableException

    getUseFastbootErase

    public boolean getUseFastbootErase ()

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

    devoluções
    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.

    Parâmetros
    userId int

    devoluções
    int the flags associated with the userId provided if found, -10000 in any other cases.

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

    devoluções
    the list of UserInfo objects.

    lances
    DeviceNotAvailableException

    getUserSerialNumber

    public int getUserSerialNumber (int userId)

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

    Parâmetros
    userId int

    devoluções
    int

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

    Parâmetros
    event DeviceEvent

    devoluções
    IManagedTestDevice.DeviceEventResponse

    hasFeature

    public boolean hasFeature (String feature)

    Check if a feature is available on a device.

    Parâmetros
    feature String : which format should be "feature: " or " " directly.

    devoluções
    boolean True if feature is found, false otherwise.

    lances
    DeviceNotAvailableException

    installPackage

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

    Install an Android package on device.

    Parâmetros
    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.

    devoluções
    String a String with an error code, or null if success.

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

    Parâmetros
    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.

    devoluções
    String a String with an error code, or null if success.

    lances
    DeviceNotAvailableException

    installPackageForUser

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

    Install an Android package on device for a given user.

    Parâmetros
    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.

    devoluções
    String a String with an error code, or null if success.

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

    Parâmetros
    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.

    devoluções
    String a String with an error code, or null if success.

    lances
    DeviceNotAvailableException

    invalidatePropertyCache

    public void invalidatePropertyCache ()

    isAdbRoot

    public boolean isAdbRoot ()

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    isAdbTcp

    public boolean isAdbTcp ()

    devoluções
    boolean

    isAppEnumerationSupported

    public boolean isAppEnumerationSupported ()

    Check whether platform on device supports app enumeration

    devoluções
    boolean True if app enumeration is supported, false otherwise

    lances
    DeviceNotAvailableException

    isBypassLowTargetSdkBlockSupported

    public boolean isBypassLowTargetSdkBlockSupported ()

    Check whether platform on device supports bypassing low target sdk block on app installs

    devoluções
    boolean True if bypass low target sdk block is supported, false otherwise

    lances
    DeviceNotAvailableException

    isDeviceEncrypted

    public boolean isDeviceEncrypted ()

    Returns if the device is encrypted.

    devoluções
    boolean true if the device is encrypted.

    lances
    DeviceNotAvailableException

    isDirectory

    public boolean isDirectory (String path)

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

    Parâmetros
    path String

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    isEnableAdbRoot

    public boolean isEnableAdbRoot ()

    devoluções
    boolean true if adb root should be enabled on device

    isEncryptionSupported

    public boolean isEncryptionSupported ()

    Returns if encryption is supported on the device.

    devoluções
    boolean true if the device supports encryption.

    lances
    DeviceNotAvailableException

    isExecutable

    public boolean isExecutable (String fullPath)

    Returns True if the file path on the device is an executable file, false otherwise.

    Parâmetros
    fullPath String

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    isFastbootEnabled

    public boolean isFastbootEnabled ()

    Return if fastboot is available for the device.

    devoluções
    boolean

    isHeadless

    public boolean isHeadless ()

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

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    isHeadlessSystemUserMode

    public boolean isHeadlessSystemUserMode ()

    Returns whether the device uses headless system user mode.

    devoluções
    boolean

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

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    isMultiUserSupported

    public boolean isMultiUserSupported ()

    Determines if multi user is supported.

    devoluções
    boolean true if multi user is supported, false otherwise

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

    Parâmetros
    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.

    devoluções
    boolean True if the package is reported as installed. False otherwise.

    lances
    DeviceNotAvailableException

    isPackageInstalled

    public boolean isPackageInstalled (String packageName)

    Query the device for a given package name to check if it's currently installed or not.

    Parâmetros
    packageName String

    devoluções
    boolean True if the package is reported as installed. False otherwise.

    lances
    DeviceNotAvailableException

    isRuntimePermissionSupported

    public boolean isRuntimePermissionSupported ()

    Check whether platform on device supports runtime permission granting

    devoluções
    boolean True if runtime permission are supported, false otherwise.

    lances
    DeviceNotAvailableException

    isStateBootloaderOrFastbootd

    public boolean isStateBootloaderOrFastbootd ()

    Returns true if device is in TestDeviceState#FASTBOOT or TestDeviceState.FASTBOOTD .

    devoluções
    boolean

    isUserRunning

    public boolean isUserRunning (int userId)

    Check if a given user is running.

    Parâmetros
    userId int

    devoluções
    boolean True if the user is running, false in every other cases.

    lances
    DeviceNotAvailableException

    isUserSecondary

    public boolean isUserSecondary (int userId)

    Return whether the specified user is a secondary user according to it's flags.

    Parâmetros
    userId int

    devoluções
    boolean true if the user is secondary, false otherwise.

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

    Parâmetros
    userId int

    devoluções
    boolean

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

    Parâmetros
    userId int

    displayId int

    devoluções
    boolean

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

    devoluções
    boolean

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

    devoluções
    boolean

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

    devoluções
    boolean true if wifi is enabled. false if disabled

    lances
    DeviceNotAvailableException

    listDisplayIds

    public  listDisplayIds ()

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

    devoluções
    The list of displays. Default always returns the default display 0.

    lances
    DeviceNotAvailableException

    listDisplayIdsForStartingVisibleBackgroundUsers

    public  listDisplayIdsForStartingVisibleBackgroundUsers ()

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

    devoluções

    lances
    DeviceNotAvailableException

    listUsers

    public  listUsers ()

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

    devoluções
    the list of user ids.

    lances
    DeviceNotAvailableException

    logAnrs

    public boolean logAnrs (ITestLogger logger)

    Collects and log ANRs from the device.

    Parâmetros
    logger ITestLogger : an ITestLogger to log the ANRs.

    devoluções
    boolean True if the logging was successful, false otherwise.

    lances
    DeviceNotAvailableException

    logBugreport

    public boolean logBugreport (String dataName, 
                    ITestLogger listener)

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

    Parâmetros
    dataName String : name under which the bugreport will be reported.

    listener ITestLogger : an ITestLogger to log the bugreport.

    devoluções
    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.

    Parâmetros
    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.

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

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

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

    lances
    DeviceNotAvailableException

    postInvocationTearDown

    public void postInvocationTearDown (Throwable exception)

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

    Parâmetros
    exception Throwable : if any, the final exception raised by the invocation failure.

    preInvocationSetup

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

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

    Parâmetros
    info IBuildInfo : The IBuildInfo of the device.

    attributes MultiMap : The attributes stored in the invocation context

    lances
    DeviceNotAvailableException
    TargetSetupError

    pullDir

    public boolean pullDir (String deviceFilePath, 
                    File localDir)

    Recursively pull directory contents from device.

    Parâmetros
    deviceFilePath String : the absolute file path of the remote source

    localDir File : the local directory to pull files into

    devoluções
    boolean true if file was pulled successfully. false otherwise.

    lances
    DeviceNotAvailableException

    pullFile

    public boolean pullFile (String remoteFilePath, 
                    File localFile)

    Retrieves a file off device.

    Parâmetros
    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.

    devoluções
    boolean true if file was retrieved successfully. false otherwise.

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

    Parâmetros
    remoteFilePath String : the absolute path to file on device.

    userId int : The user id to pull from

    devoluções
    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)

    lances
    DeviceNotAvailableException

    pullFile

    public File pullFile (String remoteFilePath)

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

    Parâmetros
    remoteFilePath String : the absolute path to file on device.

    devoluções
    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)

    lances
    DeviceNotAvailableException

    pullFile

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

    Retrieves a file off device.

    Parâmetros
    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

    devoluções
    boolean true if file was retrieved successfully. false otherwise.

    lances
    DeviceNotAvailableException

    pullFileContents

    public String pullFileContents (String remoteFilePath)

    Retrieves a file off device, and returns the contents.

    Parâmetros
    remoteFilePath String : the absolute path to file on device.

    devoluções
    String A String containing the contents of the device file, or null if the copy failed for any reason (including problems with the host filesystem)

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

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

    devoluções
    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)

    lances
    DeviceNotAvailableException

    pushDir

    public boolean pushDir (File localFileDir, 
                    String deviceFilePath, 
                     excludedDirectories)

    Recursively push directory contents to device while excluding some directories that are filtered.

    Parâmetros
    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.

    devoluções
    boolean true if file was pushed successfully. false otherwise.

    lances
    DeviceNotAvailableException

    pushDir

    public boolean pushDir (File localFileDir, 
                    String deviceFilePath)

    Recursively push directory contents to device.

    Parâmetros
    localFileDir File : the local directory to push

    deviceFilePath String : the absolute file path of the remote destination

    devoluções
    boolean true if file was pushed successfully. false otherwise.

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

    Parâmetros
    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

    devoluções
    boolean true if file was pushed successfully. false otherwise.

    lances
    DeviceNotAvailableException

    pushFile

    public boolean pushFile (File localFile, 
                    String remoteFilePath)

    Push a file to device. By default using a content provider.

    Parâmetros
    localFile File : the local file to push

    remoteFilePath String : the remote destination absolute file path

    devoluções
    boolean true if file was pushed successfully. false otherwise.

    lances
    DeviceNotAvailableException

    pushString

    public boolean pushString (String contents, 
                    String remoteFilePath)

    Push file created from a string to device

    Parâmetros
    contents String : the contents of the file to push

    remoteFilePath String : the remote destination absolute file path

    devoluções
    boolean true if string was pushed successfully. false otherwise.

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

    Parâmetros
    reason String : a reason for this reboot, or null if no reason is specified.

    lances
    DeviceNotAvailableException

    reboot

    public void reboot ()

    Reboots the device into adb mode.

    Blocks until device becomes available.

    lances
    DeviceNotAvailableException

    rebootIntoBootloader

    public void rebootIntoBootloader ()

    Reboots the device into bootloader mode.

    Blocks until device is in bootloader mode.

    lances
    DeviceNotAvailableException

    rebootIntoFastbootd

    public void rebootIntoFastbootd ()

    Reboots the device into fastbootd mode.

    Blocks until device is in fastbootd mode.

    lances
    DeviceNotAvailableException

    rebootIntoRecovery

    public void rebootIntoRecovery ()

    Reboots the device into adb recovery mode.

    Blocks until device enters recovery

    lances
    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

    lances
    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

    Parâmetros
    autoReboot boolean : whether to automatically reboot the device after sideload

    lances
    DeviceNotAvailableException

    rebootUntilOnline

    public void rebootUntilOnline ()

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

    lances
    DeviceNotAvailableException

    rebootUntilOnline

    public void rebootUntilOnline (String reason)

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

    Parâmetros
    reason String : a reason for this reboot, or null if no reason is specified.

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

    lances
    DeviceNotAvailableException

    rebootUserspaceUntilOnline

    public void rebootUserspaceUntilOnline ()

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

    lances
    DeviceNotAvailableException

    recoverDevice

    public boolean recoverDevice ()

    Attempts to recover device communication.

    devoluções
    boolean True if recovery attempted and successful, returns False if recovery was skipped

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

    Parâmetros
    deviceActionReceiver IDeviceActionReceiver : A IDeviceActionReceiver which will be registered.

    remountSystemReadOnly

    public void remountSystemReadOnly ()

    Make the system partition on the device read-only. May reboot the device.

    lances
    DeviceNotAvailableException

    remountSystemWritable

    public void remountSystemWritable ()

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

    lances
    DeviceNotAvailableException

    remountVendorReadOnly

    public void remountVendorReadOnly ()

    Make the vendor partition on the device read-only. May reboot the device.

    lances
    DeviceNotAvailableException

    remountVendorWritable

    public void remountVendorWritable ()

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

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

    Parâmetros
    componentName String : of device admin to be removed.

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

    devoluções
    boolean True if it is successful, false otherwise.

    lances
    DeviceNotAvailableException

    removeOwners

    public void removeOwners ()

    Remove all existing device profile owners with the best effort.

    lances
    DeviceNotAvailableException

    removeUser

    public boolean removeUser (int userId)

    Remove a given user from the device.

    Parâmetros
    userId int : of the user to remove

    devoluções
    boolean true if we were successful in removing the user, false otherwise.

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

    Parâmetros
    runner IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests

    listeners ITestLifeCycleReceiver : the test result listener(s)

    devoluções
    boolean true if test command completed. false if it failed to complete, but recovery succeeded

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

    Parâmetros
    runner IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests

    listeners : the test result listeners

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

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

    Parâmetros
    runner IRemoteAndroidTestRunner

    userId int

    listeners

    devoluções
    boolean

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

    Parâmetros
    runner IRemoteAndroidTestRunner

    userId int

    listeners ITestLifeCycleReceiver

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    setConfiguration

    public void setConfiguration (IConfiguration configuration)

    Injects the IConfiguration in use.

    Parâmetros
    configuration IConfiguration

    setConnectionAvdInfo

    public final void setConnectionAvdInfo (GceAvdInfo avdInfo)

    Parâmetros
    avdInfo GceAvdInfo

    setDate

    public void setDate (Date date)

    Sets the date on device

    Note: setting date on device requires root

    Parâmetros
    date Date : specify a particular date; will use host date if null

    lances
    DeviceNotAvailableException

    setDeviceOwner

    public boolean setDeviceOwner (String componentName, 
                    int userId)

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

    Parâmetros
    componentName String : of device admin to be device owner.

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

    devoluções
    boolean True if it is successful, false otherwise.

    lances
    DeviceNotAvailableException

    setDeviceState

    public void setDeviceState (TestDeviceState deviceState)

    Update the device's state.

    Parâmetros
    deviceState TestDeviceState : the TestDeviceState

    setEmulatorOutputStream

    public void setEmulatorOutputStream (SizeLimitedOutputStream output)

    For emulator set SizeLimitedOutputStream to log output

    Parâmetros
    output SizeLimitedOutputStream : to log the output

    setEmulatorProcess

    public void setEmulatorProcess (Process p)

    Sets the Process , when this device is an emulator.

    Parâmetros
    p Process

    setFastbootEnabled

    public void setFastbootEnabled (boolean fastbootEnabled)

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

    Parâmetros
    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.

    Parâmetros
    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

    Parâmetros
    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.

    Parâmetros
    delay int : the delay in ms

    setOptions

    public void setOptions (TestDeviceOptions options)

    Set the TestDeviceOptions for the device

    Parâmetros
    options TestDeviceOptions

    setProperty

    public boolean setProperty (String propKey, 
                    String propValue)

    Sets the given property value on the device. Requires adb root is true.

    Parâmetros
    propKey String : The key targeted to be set.

    propValue String : The property value to be set.

    devoluções
    boolean returns True if the setprop command was successful, False otherwise.

    lances
    DeviceNotAvailableException

    setRecovery

    public void setRecovery (IDeviceRecovery recovery)

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

    Parâmetros
    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

    Parâmetros
    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.

    Parâmetros
    namespace String

    key String

    value String

    lances
    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"}

    Parâmetros
    userId int

    namespace String

    key String

    value String

    lances
    DeviceNotAvailableException

    setTestLogger

    public void setTestLogger (ITestLogger testLogger)

    Injects the ITestLogger instance

    Parâmetros
    testLogger ITestLogger

    setUseFastbootErase

    public void setUseFastbootErase (boolean useFastbootErase)

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

    Parâmetros
    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.

    Parâmetros
    userId int : of the user to start in the background

    devoluções
    boolean true if the user was successfully started in the background.

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

    Parâmetros
    userId int : of the user to start in the background

    waitFlag boolean : will make the command wait until user is started and unlocked.

    devoluções
    boolean true if the user was successfully started in the background.

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

    Parâmetros
    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.

    devoluções
    boolean true if the user was successfully started visible in the background.

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

    Parâmetros
    userId int : of the user to stop.

    devoluções
    boolean true if the user was successfully stopped.

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

    Parâmetros
    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.

    devoluções
    boolean true if the user was successfully stopped.

    lances
    DeviceNotAvailableException

    switchToAdbTcp

    public String switchToAdbTcp ()

    Switch device to adb-over-tcp mode.

    devoluções
    String the tcp serial number or null if device could not be switched

    lances
    DeviceNotAvailableException

    switchToAdbUsb

    public boolean switchToAdbUsb ()

    Switch device to adb over usb mode.

    devoluções
    boolean true if switch was successful, false otherwise.

    lances
    DeviceNotAvailableException

    switchUser

    public boolean switchUser (int userId)

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

    Parâmetros
    userId int

    devoluções
    boolean True if the new userId matches the userId provider. False otherwise.

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

    Parâmetros
    userId int

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

    devoluções
    boolean True if the new userId matches the userId provider. False otherwise.

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

    Parâmetros
    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

    devoluções
    boolean true if files were synced successfully. false otherwise.

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

    devoluções
    Bugreport

    uninstallPackage

    public String uninstallPackage (String packageName)

    Uninstall an Android package from device.

    Parâmetros
    packageName String : the Android package to uninstall

    devoluções
    String a String with an error code, or null if success.

    lances
    DeviceNotAvailableException

    uninstallPackageForUser

    public String uninstallPackageForUser (String packageName, 
                    int userId)

    Uninstall an Android package from device for a given user.

    Parâmetros
    packageName String : the Android package to uninstall

    userId int : the integer user id to uninstall for.

    devoluções
    String a String with an error code, or null if success.

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

    devoluções
    boolean true if successful or if the device is unencrypted.

    lances
    DeviceNotAvailableException

    waitForBootComplete

    public boolean waitForBootComplete (long timeOut)

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

    Parâmetros
    timeOut long : time in msecs to wait for the flag to be set

    devoluções
    boolean true if device's boot complete flag is set within the timeout

    lances
    DeviceNotAvailableException

    waitForDeviceAvailable

    public boolean waitForDeviceAvailable ()

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

    devoluções
    boolean True if device is available, False if recovery is disabled and unavailable.

    lances
    DeviceNotAvailableException

    waitForDeviceAvailable

    public boolean waitForDeviceAvailable (long waitTime)

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

    Parâmetros
    waitTime long : the time in ms to wait

    devoluções
    boolean True if device is available, False if recovery is disabled and unavailable.

    lances
    DeviceNotAvailableException

    waitForDeviceAvailableInRecoverPath

    public boolean waitForDeviceAvailableInRecoverPath (long waitTime)

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

    Parâmetros
    waitTime long

    devoluções
    boolean True if device is available, False if unavailable.

    lances
    DeviceNotAvailableException

    waitForDeviceBootloader

    public void waitForDeviceBootloader ()

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

    lances
    DeviceNotAvailableException

    waitForDeviceInRecovery

    public boolean waitForDeviceInRecovery (long waitTime)

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

    Parâmetros
    waitTime long : the time in ms to wait

    devoluções
    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

    Parâmetros
    waitTime long : the time in ms to wait

    devoluções
    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

    Parâmetros
    waitTime long : the time in ms to wait

    devoluções
    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.

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

    Parâmetros
    waitTime long : the time in ms to wait

    lances
    DeviceNotAvailableException

    waitForDeviceShell

    public boolean waitForDeviceShell (long waitTime)

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

    Parâmetros
    waitTime long : the time in ms to wait

    devoluções
    boolean true if device becomes responsive before waitTime elapses.

    Métodos protegidos

    addExtraConnectionBuilderArgs

    protected void addExtraConnectionBuilderArgs (DefaultConnection.ConnectionBuilder builder)

    Parâmetros
    builder DefaultConnection.ConnectionBuilder

    buildAdbShellCommand

    protected String[] buildAdbShellCommand (String command, 
                    boolean forceExitStatusDetection)

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

    Parâmetros
    command String

    forceExitStatusDetection boolean

    devoluções
    String[]

    checkApiLevelAgainst

    protected void checkApiLevelAgainst (String feature, 
                    int strictMinLevel)

    Parâmetros
    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.

    Parâmetros
    rebootMode NativeDevice.RebootMode : a mode of this reboot.

    reason String : for this reboot.

    devoluções
    NativeDevice.RebootDeviceAction the created RebootDeviceAction .

    createRunUtil

    protected IRunUtil createRunUtil ()

    devoluções
    IRunUtil

    doAdbReboot

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

    Perform a adb reboot.

    Parâmetros
    rebootMode NativeDevice.RebootMode : a mode of this reboot.

    reason String : for this reboot.

    lances
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    ensureRuntimePermissionSupported

    protected void ensureRuntimePermissionSupported ()

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

    lances
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    getApiLevelSafe

    protected int getApiLevelSafe ()

    devoluções
    int

    getLogger

    protected ITestLogger getLogger ()

    devoluções
    ITestLogger

    getRunUtil

    protected IRunUtil getRunUtil ()

    Get the RunUtil instance to use.

    devoluções
    IRunUtil

    initializeConnection

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

    Parâmetros
    info IBuildInfo

    attributes MultiMap

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

    Parâmetros
    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.

    devoluções
    String A string, possibly null or empty, containing the value of the given property

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

    devoluções
    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.

    Parâmetros
    localFile File

    entry IFileEntry

    devoluções
    boolean

    notifyRebootEnded

    protected void notifyRebootEnded ()

    Notifies all IDeviceActionReceiver about reboot end event.

    lances
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    notifyRebootStarted

    protected void notifyRebootStarted ()

    Notifies all IDeviceActionReceiver about reboot start event.

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

    Parâmetros
    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

    devoluções
    boolean true if action was performed successfully

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

    postAdbReboot

    protected void postAdbReboot ()

    Possible extra actions that can be taken after a reboot.

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

    lances
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    pullFileInternal

    protected boolean pullFileInternal (String remoteFilePath, 
                    File localFile)

    Parâmetros
    remoteFilePath String

    localFile File

    devoluções
    boolean

    lances
    DeviceNotAvailableException

    setClock

    protected void setClock (Clock clock)

    Set the Clock instance to use.

    Parâmetros
    clock Clock

    setMicrodroidProcess

    protected void setMicrodroidProcess (Process process)

    Marks the TestDevice as microdroid and sets its CID.

    Parâmetros
    process Process : Process of the Microdroid VM.

    setTestDeviceOptions

    protected void setTestDeviceOptions ( deviceOptions)

    Parâmetros
    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.

    Parâmetros
    timeout long

    envVarMap

    fullCmd String

    devoluções
    CommandResult

    simpleFastbootCommand

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

    Executes a simple fastboot command and report the status of the command.

    Parâmetros
    timeout long

    fullCmd String

    devoluções
    CommandResult

    waitForDeviceNotAvailable

    protected boolean waitForDeviceNotAvailable (String operationDesc, 
                    long time)

    Wait to see the device going unavailable (stop reporting to adb).

    Parâmetros
    operationDesc String : The name of the operation that is waiting for unavailable.

    time long : The time to wait for unavailable to occur.

    devoluções
    boolean True if device did become unavailable.