Dispositivo nativo
public class NativeDevice
extends Object
implements IManagedTestDevice , IConfigurationReceiver , ITestLoggerReceiver
java.lang.Objeto | |
↳ | com.android.tradefed.device.NativeDevice |
Implementación predeterminada de un ITestDevice
Dispositivos Android de pila no completa.
Resumen
Clases anidadas | |
---|---|
class | NativeDevice.AdbAction Un |
class | NativeDevice.AdbShellAction |
class | NativeDevice.RebootDeviceAction |
constantes | |
---|---|
int | INVALID_USER_ID Valor devuelto para cualquier identificación de usuario no válida/no encontrada: UserHandle definió el valor -10000 |
long | MAX_HOST_DEVICE_TIME_OFFSET |
int | MAX_RETRY_ATTEMPTS el número predeterminado de intentos de reintento de comando para realizar |
Campos | |
---|---|
protected static final String | SD_CARD |
protected static final String | STORAGE_EMULATED |
protected TestDeviceOptions | mOptions |
protected final IDeviceStateMonitor | mStateMonitor
|
Constructores públicos | |
---|---|
NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor) Crea un |
Métodos públicos | |
---|---|
boolean | canSwitchToHeadlessSystemUser () Devuelve si está permitido cambiar al usuario del SISTEMA sin cabeza. |
boolean | checkApiLevelAgainstNextRelease (int strictMinLevel) Compruebe si una función es compatible actualmente o no dado un nivel mínimo compatible. |
boolean | checkConnectivity () Compruebe que el dispositivo tiene conectividad de red. |
boolean | clearErrorDialogs () Intente descartar los cuadros de diálogo de error que se muestran actualmente en la interfaz de usuario del dispositivo. |
void | clearLastConnectedWifiNetwork () Borra la última red wifi conectada. |
void | clearLogcat () Elimina cualquier dato logcat acumulado. |
boolean | connectToWifiNetwork ( wifiSsidToPsk, boolean scanSsid) connectToWifiNetwork ( wifiSsidToPsk, boolean scanSsid) Se conecta a una red wifi. |
boolean | connectToWifiNetwork (String wifiSsid, String wifiPsk) Se conecta a una red wifi. |
boolean | connectToWifiNetwork ( wifiSsidToPsk) connectToWifiNetwork ( wifiSsidToPsk) Se conecta a una red wifi.f |
boolean | connectToWifiNetwork (String wifiSsid, String wifiPsk, boolean scanSsid) Se conecta a una red wifi. |
boolean | connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk, boolean scanSsid) Una variante de |
boolean | connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk) Una variante de |
int | createUser (String name, boolean guest, boolean ephemeral) Cree un usuario con un nombre dado y las banderas proporcionadas |
int | createUser (String name, boolean guest, boolean ephemeral, boolean forTesting) Cree un usuario con un nombre dado y las banderas proporcionadas |
int | createUser (String name) Cree un usuario con un nombre dado y banderas predeterminadas 0. |
int | createUserNoThrow (String name) Cree un usuario con un nombre dado y banderas predeterminadas 0. |
void | deleteFile (String deviceFilePath) Método auxiliar para eliminar un archivo o directorio en el dispositivo. |
void | deregisterDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver) Elimina el |
boolean | deviceSoftRestarted ( ProcessInfo prevSystemServerProcess) Método de ayuda para verificar si el dispositivo se reinició por software al comparar system_server actual con system_server |
boolean | deviceSoftRestartedSince (long utcEpochTime, TimeUnit timeUnit) Método auxiliar para comprobar si el dispositivo se reinició desde la hora UTC desde la época del dispositivo y su |
boolean | disableAdbRoot () Desactiva adb root. |
void | disableKeyguard () Intenta desactivar el bloqueo del teclado. |
boolean | disableNetworkMonitor () Desactiva la supervisión de la red en el dispositivo. |
boolean | disconnectFromWifi () Se desconecta de una red wifi. |
boolean | doesFileExist (String deviceFilePath, int userId) Método auxiliar para determinar si existe un archivo en el dispositivo para un usuario determinado. |
boolean | doesFileExist (String deviceFilePath) Método auxiliar para determinar si existe un archivo en el dispositivo. |
File | dumpHeap (String process, String devicePath) Intente volcar el montón de system_server. |
boolean | enableAdbRoot () Activa adb root. |
boolean | enableNetworkMonitor () Habilita el monitoreo de la red en el dispositivo. |
String | executeAdbCommand (long timeout, String... cmdArgs) Método auxiliar que ejecuta un comando adb como un comando del sistema con un tiempo de espera especificado. |
String | executeAdbCommand (long timeout, envMap, String... cmdArgs) executeAdbCommand (long timeout, envMap, String... cmdArgs) Método auxiliar que ejecuta un comando adb como un comando del sistema con un tiempo de espera especificado. |
String | executeAdbCommand (String... cmdArgs) Método auxiliar que ejecuta un comando adb como un comando del sistema. |
CommandResult | executeFastbootCommand (String... cmdArgs) Método auxiliar que ejecuta un comando fastboot como un comando del sistema con un tiempo de espera predeterminado de 2 minutos. |
CommandResult | executeFastbootCommand (long timeout, String... cmdArgs) Método auxiliar que ejecuta un comando fastboot como un comando del sistema. |
CommandResult | executeLongFastbootCommand (String... cmdArgs) Método auxiliar que ejecuta un comando fastboot de ejecución prolongada como un comando del sistema. |
CommandResult | executeLongFastbootCommand ( envVarMap, String... cmdArgs) executeLongFastbootCommand ( envVarMap, String... cmdArgs) Método auxiliar que ejecuta un comando fastboot de ejecución prolongada como un comando del sistema con variables de entorno del sistema. |
String | executeShellCommand (String command) Método auxiliar que ejecuta un comando adb shell y devuelve el resultado como |
void | executeShellCommand (String command, IShellOutputReceiver receiver, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts) Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando. |
void | executeShellCommand (String command, IShellOutputReceiver receiver, long maxTimeoutForCommand, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts) Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando. |
void | executeShellCommand (String command, IShellOutputReceiver receiver) Ejecuta el comando adb shell dado y vuelve a intentarlo varias veces si el comando falla. |
CommandResult | executeShellV2Command (String cmd) Método auxiliar que ejecuta un comando de shell adb y devuelve los resultados como un |
CommandResult | executeShellV2Command (String cmd, OutputStream pipeToOutput) Método auxiliar que ejecuta un comando de shell adb y devuelve los resultados como un |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput) Método auxiliar que ejecuta un comando de shell adb y devuelve los resultados como un |
CommandResult | executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts) Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando. |
CommandResult | executeShellV2Command (String cmd, long maxTimeoutForCommand, TimeUnit timeUnit) Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando. |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts) Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando. |
CommandResult | executeShellV2Command (String cmd, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, long maxTimeoutForCommand, TimeUnit timeUnit, int retryAttempts) Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando. |
CommandResult | fastbootWipePartition (String partition) Método auxiliar que borra una partición del dispositivo. |
getActiveApexes () Obtenga la información sobre los APEX activados en el dispositivo. | |
getAllSettings (String namespace) Devuelve pares de valores clave del espacio de nombres solicitado. | |
DeviceAllocationState | getAllocationState () Devuelve el estado de asignación actual del dispositivo |
String | getAndroidId (int userId) Busque y devuelva el ID de Android asociado a un ID de usuario, nulo si no se encuentra. |
getAndroidIds () Cree un mapa de ID de Android que coincidan con los ID de usuario. | |
int | getApiLevel () Obtenga el nivel de API del dispositivo. |
PackageInfo | getAppPackageInfo (String packageName) Obtenga información sobre un paquete instalado en el dispositivo. |
getAppPackageInfos () Obtener información de los paquetes instalados en el dispositivo. | |
String | getBasebandVersion () Método conveniente para obtener la versión de banda base (radio) de este dispositivo. |
Integer | getBattery () Devuelve el nivel de batería actual de un dispositivo o Nulo si el nivel de batería no está disponible. |
boolean | getBooleanProperty (String name, boolean defaultValue) Devuelve el valor booleano de la propiedad dada. |
getBootHistory () El método auxiliar recopila el mapa del historial de arranque con el tiempo de arranque y el motivo del arranque. | |
getBootHistorySince (long utcEpochTime, TimeUnit timeUnit) El método auxiliar recopila el mapa del historial de arranque con la hora de arranque y el motivo de arranque desde la hora dada desde la época del dispositivo y la unidad de tiempo especificada. | |
String | getBootloaderVersion () Método de conveniencia para obtener la versión del gestor de arranque de este dispositivo. |
InputStreamSource | getBugreport () Recupera un informe de error del dispositivo. |
InputStreamSource | getBugreportz () Recupera un bugreportz del dispositivo. |
String | getBuildAlias () Recupere el alias de la compilación que el dispositivo está ejecutando actualmente. |
String | getBuildFlavor () Recupere el tipo de compilación para el dispositivo. |
String | getBuildId () Recupere la compilación que el dispositivo está ejecutando actualmente. |
String | getBuildSigningKeys () Devuelve el tipo de clave utilizada para firmar la imagen del dispositivo. Por lo general, los dispositivos Android pueden firmarse con claves de prueba (como en AOSP) o claves de liberación (controladas por fabricantes de dispositivos individuales) |
DeviceDescriptor | getCachedDeviceDescriptor () Devuelve un |
DeviceDescriptor | getCachedDeviceDescriptor (boolean shortDescriptor) Devuelve un |
String[] | getChildren (String path) Alternativa al uso |
AbstractConnection | getConnection () La conexión actual asociada con el dispositivo. |
DeviceFoldableState | getCurrentFoldableState () Devuelve el estado plegable actual del dispositivo o nulo si ocurrieron algunos problemas. |
int | getCurrentUser () Devuelve la identificación del usuario actual en ejecución. |
String | getDeviceClass () Obtenga la clase de dispositivo. |
long | getDeviceDate () Devuelve la fecha del dispositivo en milisegundos desde la época. |
DeviceDescriptor | getDeviceDescriptor () Devuelve un |
DeviceDescriptor | getDeviceDescriptor (boolean shortDescriptor) Devuelve un |
TestDeviceState | getDeviceState () Obtener el estado del dispositivo. |
long | getDeviceTimeOffset (Date date) Ayudante para obtener la diferencia horaria entre el dispositivo y un |
InputStreamSource | getEmulatorOutput () Obtenga la transmisión del emulador stdout y stderr |
Process | getEmulatorProcess () Devuelve el |
final File | getExecuteShellCommandLog () El registro que contiene todos los registros |
long | getExternalStoreFreeSpace () Método auxiliar para determinar la cantidad de espacio libre en el almacenamiento externo del dispositivo. |
String | getFastbootPath () Devuelve la ruta del binario fastboot que se está utilizando. |
String | getFastbootProductType () Método conveniente para obtener el tipo de producto de este dispositivo cuando está en modo fastboot. |
String | getFastbootProductVariant () Método conveniente para obtener el tipo de producto de este dispositivo cuando está en modo fastboot. |
String | getFastbootSerialNumber () Devuelve el número de serie del modo fastboot. |
String | getFastbootVariable (String variableName) Recupere el valor de la variable fastboot dado del dispositivo. |
String | getFastbootVersion () Devuelve la cadena de versión del binario fastboot que se está utilizando. |
IFileEntry | getFileEntry (String path) Recupere una referencia a un archivo remoto en el dispositivo. |
IFileEntry | getFileEntry (FileListingService.FileEntry entry) Ayudante no oficial para obtener una |
getFoldableStates () Devuelve la lista de estados plegables en el dispositivo. | |
IDevice | getIDevice () Devuelve una referencia al |
getInstalledPackageNames () Obtenga los nombres de los paquetes de aplicaciones presentes en el dispositivo. | |
long | getIntProperty (String name, long defaultValue) Devuelve el valor entero de la propiedad dada del dispositivo. |
String | getIpAddress () Obtiene la dirección IP del dispositivo. |
KeyguardControllerState | getKeyguardState () Devuelve un objeto para obtener el estado actual del bloqueo de teclado o nulo si no es compatible. |
long | getLastExpectedRebootTimeMillis () Devuelve la última vez que las API de Tradefed activaron un reinicio en milisegundos desde EPOCH según lo devuelto por |
int | getLaunchApiLevel () Obtenga el primer nivel de API lanzado del dispositivo. |
InputStreamSource | getLogcat () Toma una secuencia instantánea de los datos logcat. |
InputStreamSource | getLogcat (int maxBytes) Toma un flujo de instantáneas de los últimos |
InputStreamSource | getLogcatDump () Obtenga un volcado del logcat actual para el dispositivo. |
InputStreamSource | getLogcatSince (long date) Toma un flujo de instantáneas de los datos de logcat capturados a partir de la fecha proporcionada. |
String | getMacAddress () Devuelve la dirección MAC del dispositivo, nula si no se consulta desde el dispositivo. |
Integer | getMainUserId () Devuelve el ID de usuario principal. |
getMainlineModuleInfo () Obtenga la información sobre los módulos principales instalados en el dispositivo. | |
int | getMaxNumberOfRunningUsersSupported () Obtenga la cantidad máxima de usuarios compatibles que se ejecutan simultáneamente. |
int | getMaxNumberOfUsersSupported () Obtenga el número máximo de usuarios admitidos. |
Process | getMicrodroidProcess () |
IDeviceStateMonitor | getMonitor () Devuelve el |
String | getMountPoint (String mountName) Devuelve un punto de montaje. |
ITestDevice.MountPointInfo | getMountPointInfo (String mountpoint) Devuelve un |
getMountPointInfo () Devuelve una versión analizada de la información en /proc/mounts en el dispositivo | |
TestDeviceOptions | getOptions () Obtener las opciones de prueba para el dispositivo. |
long | getPartitionFreeSpace (String partition) Método auxiliar para determinar la cantidad de espacio libre en la partición del dispositivo. |
Integer | getPrimaryUserId () Devuelve el ID de usuario principal. |
ProcessInfo | getProcessByName (String processName) El método auxiliar ejecuta el comando "pidof" y "stat" y devuelve el objeto |
String | getProcessPid (String process) Devuelve el pid del servicio o nulo si algo salió mal. |
String | getProductType () Método de conveniencia para obtener el tipo de producto de este dispositivo. |
String | getProductVariant () Método de conveniencia para obtener la variante de producto de este dispositivo. |
String | getProperty (String name) Recuperar el valor de propiedad dado del dispositivo. |
ITestDevice.RecoveryMode | getRecoveryMode () Obtenga el modo de recuperación actual utilizado para el dispositivo. |
InputStreamSource | getScreenshot (String format) Toma una captura de pantalla del dispositivo. |
InputStreamSource | getScreenshot (long displayId) Toma una captura de pantalla del dispositivo con la identificación de pantalla dada. |
InputStreamSource | getScreenshot (String format, boolean rescale) Toma una captura de pantalla del dispositivo. |
InputStreamSource | getScreenshot () Toma una captura de pantalla del dispositivo. |
String | getSerialNumber () Método de conveniencia para obtener el número de serie de este dispositivo. |
String | getSetting (int userId, String namespace, String key) Devuelve el valor de la configuración solicitada. |
String | getSetting (String namespace, String key) Ver |
String | getSimOperator () Devuelve el operador de la tarjeta SIM o nulo si no está disponible o si el dispositivo no está disponible. |
String | getSimState () Devuelve el estado de la tarjeta SIM o nulo si no está disponible o el dispositivo no está disponible. |
getTombstones () Obtenga y devuelva la lista de lápidas de los dispositivos. | |
long | getTotalMemory () Devuelve el tamaño total de la memoria física en bytes o -1 en caso de error interno |
getUninstallablePackageNames () Obtenga los nombres de los paquetes de aplicaciones que se pueden desinstalar. | |
boolean | getUseFastbootErase () Obtenga información sobre si usar el borrado de inicio rápido o el formato de inicio rápido para borrar una partición en el dispositivo. |
int | getUserFlags (int userId) Encuentra y devuelve las banderas de un usuario dado. |
getUserInfos () Obtiene el mapa de useId a | |
int | getUserSerialNumber (int userId) Devuelve el número de serie asociado al ID de usuario si se encuentra, -10000 en cualquier otro caso. |
IManagedTestDevice.DeviceEventResponse | handleAllocationEvent (DeviceEvent event) Procese el Procese el DeviceEvent, que puede o no hacer la transición de este dispositivo a un nuevo estado de asignación. |
boolean | hasFeature (String feature) Compruebe si una función está disponible en un dispositivo. |
String | installPackage (File packageFile, boolean reinstall, String... extraArgs) Instale un paquete de Android en el dispositivo. |
String | installPackage (File packageFile, boolean reinstall, boolean grantPermissions, String... extraArgs) Instale un paquete de Android en el dispositivo. |
String | installPackageForUser (File packageFile, boolean reinstall, int userId, String... extraArgs) Instale un paquete de Android en el dispositivo para un usuario determinado. |
String | installPackageForUser (File packageFile, boolean reinstall, boolean grantPermissions, int userId, String... extraArgs) Instale un paquete de Android en el dispositivo para un usuario determinado. |
boolean | isAdbRoot () |
boolean | isAdbTcp () |
boolean | isAppEnumerationSupported () Compruebe si la plataforma en el dispositivo admite la enumeración de aplicaciones |
boolean | isBypassLowTargetSdkBlockSupported () Verifique si la plataforma en el dispositivo admite la omisión del bloque SDK de destino bajo en las instalaciones de la aplicación |
boolean | isDeviceEncrypted () Devuelve si el dispositivo está encriptado. |
boolean | isDirectory (String path) Retorna True si la ruta en el dispositivo es un directorio, false en caso contrario. |
boolean | isEnableAdbRoot () |
boolean | isEncryptionSupported () Devuelve si el cifrado es compatible con el dispositivo. |
boolean | isExecutable (String fullPath) Devuelve True si la ruta del archivo en el dispositivo es un archivo ejecutable; de lo contrario, devuelve false. |
boolean | isFastbootEnabled () Vuelve si fastboot está disponible para el dispositivo. |
boolean | isHeadless () Devuelve verdadero si el dispositivo no tiene cabeza (sin pantalla), falso en caso contrario. |
boolean | isHeadlessSystemUserMode () Devuelve si el dispositivo usa el modo de usuario del sistema sin cabeza. |
boolean | isMainUserPermanentAdmin () Devuelve si el usuario principal es un administrador permanente y no se puede eliminar o degradar al estado de no administrador. |
boolean | isMultiUserSupported () Determina si se admite multiusuario. |
boolean | isPackageInstalled (String packageName, String userId) Consulte el dispositivo para obtener un nombre de paquete dado y una identificación de usuario dada para verificar si está instalado actualmente o no para ese usuario. |
boolean | isPackageInstalled (String packageName) Consulte el dispositivo por un nombre de paquete dado para verificar si está instalado actualmente o no. |
boolean | isRuntimePermissionSupported () Compruebe si la plataforma en el dispositivo admite la concesión de permisos de tiempo de ejecución |
boolean | isStateBootloaderOrFastbootd () Devuelve verdadero si el dispositivo está en |
boolean | isUserRunning (int userId) Compruebe si un usuario determinado se está ejecutando. |
boolean | isUserSecondary (int userId) Devuelve si el usuario especificado es un usuario secundario según sus indicadores. |
boolean | isUserVisible (int userId) Comprueba si el usuario dado es visible. |
boolean | isUserVisibleOnDisplay (int userId, int displayId) Comprueba si el usuario dado está visible en la pantalla dada. |
boolean | isVisibleBackgroundUsersOnDefaultDisplaySupported () Devuelve si el dispositivo permite que los usuarios se inicien visibles en segundo plano en el |
boolean | isVisibleBackgroundUsersSupported () Devuelve si el dispositivo permite que los usuarios se inicien visibles en segundo plano. |
boolean | isWifiEnabled () Prueba si el wifi está habilitado. |
listDisplayIds () Recopile la lista de ID de pantallas disponibles en el dispositivo según lo informado por "dumpsys SurfaceFlinger". | |
listDisplayIdsForStartingVisibleBackgroundUsers () Obtiene la lista de pantallas que se pueden usar para | |
listUsers () Obtiene la lista de usuarios en el dispositivo. | |
boolean | logAnrs ( ITestLogger logger) Recopila y registra ANR del dispositivo. |
boolean | logBugreport (String dataName, ITestLogger listener) Método de ayuda para tomar un informe de error y registrarlo para los reporteros. |
void | logOnDevice (String tag, Log.LogLevel level, String format, Object... args) Registre un mensaje en el logcat del dispositivo. |
void | nonBlockingReboot () Emite un comando para reiniciar el dispositivo y regresa al completar el comando y cuando el dispositivo ya no es visible para adb. |
void | postAdbRootAction () Anule si el dispositivo necesita que se realicen algunas acciones específicas después de adb root y antes de que el dispositivo vuelva a estar en línea. |
void | postAdbUnrootAction () Anule si el dispositivo necesita que se realicen algunas acciones específicas después de adb unroot y antes de que el dispositivo vuelva a estar en línea. |
void | postBootSetup () Realice las instrucciones para configurar el dispositivo para probarlo después de cada arranque. |
void | postInvocationTearDown (Throwable exception) Pasos adicionales para la limpieza requerida específica del dispositivo que se ejecutará después de que se realice la invocación. |
void | preInvocationSetup ( IBuildInfo info, MultiMap <String, String> attributes) Pasos adicionales para la configuración requerida específica del dispositivo que se ejecutará en el dispositivo antes del flujo de invocación. |
boolean | pullDir (String deviceFilePath, File localDir) Extraiga recursivamente el contenido del directorio del dispositivo. |
boolean | pullFile (String remoteFilePath, File localFile) Recupera un archivo del dispositivo. |
File | pullFile (String remoteFilePath, int userId) Recupera un archivo del dispositivo, lo almacena en un |
File | pullFile (String remoteFilePath) Recupera un archivo del dispositivo, lo almacena en un |
boolean | pullFile (String remoteFilePath, File localFile, int userId) Recupera un archivo del dispositivo. |
String | pullFileContents (String remoteFilePath) Recupera un archivo del dispositivo y devuelve el contenido. |
File | pullFileFromExternal (String remoteFilePath) Un método práctico para recuperar un archivo del almacenamiento externo del dispositivo, almacenarlo en un |
boolean | pushDir (File localFileDir, String deviceFilePath, excludedDirectories) pushDir (File localFileDir, String deviceFilePath, excludedDirectories) Empuje recursivamente los contenidos del directorio al dispositivo mientras excluye algunos directorios que se filtran. |
boolean | pushDir (File localFileDir, String deviceFilePath) Empuje recursivamente los contenidos del directorio al dispositivo. |
boolean | pushFile (File localFile, String remoteFilePath, boolean evaluateContentProviderNeeded) Variante de |
boolean | pushFile (File localFile, String remoteFilePath) Empuje un archivo al dispositivo. |
boolean | pushString (String contents, String remoteFilePath) Empuje el archivo creado a partir de una cadena al dispositivo |
void | reboot (String reason) Reinicia el dispositivo en modo adb con |
void | reboot () Reinicia el dispositivo en modo adb. |
void | rebootIntoBootloader () Reinicia el dispositivo en modo cargador de arranque. |
void | rebootIntoFastbootd () Reinicia el dispositivo en modo fastbootd. |
void | rebootIntoRecovery () Reinicia el dispositivo en el modo de recuperación adb. |
void | rebootIntoSideload () Reinicia el dispositivo en modo adb sideload (tenga en cuenta que este es un modo especial en recuperación) Se bloquea hasta que el dispositivo ingresa al modo de carga lateral |
void | rebootIntoSideload (boolean autoReboot) Reinicia el dispositivo en modo adb sideload (tenga en cuenta que este es un modo especial en recuperación) Se bloquea hasta que el dispositivo ingresa al modo de carga lateral |
void | rebootUntilOnline () Una alternativa a |
void | rebootUntilOnline (String reason) Una alternativa a |
void | rebootUserspace () Reinicia solo la parte del espacio de usuario del dispositivo. |
void | rebootUserspaceUntilOnline () Una alternativa a |
boolean | recoverDevice () Intentos de recuperar la comunicación del dispositivo. |
void | registerDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver) Registra un |
void | remountSystemWritable () Haga que la partición del sistema en el dispositivo sea escribible. |
void | remountVendorWritable () Haga que la partición del proveedor en el dispositivo sea escribible. |
boolean | removeAdmin (String componentName, int userId) Elimine el administrador del dispositivo dado en el usuario dado y devuelva |
void | removeOwners () Elimine todos los propietarios de perfiles de dispositivos existentes con el mejor esfuerzo. |
boolean | removeUser (int userId) Eliminar un usuario determinado del dispositivo. |
void | resetContentProviderSetup () Restablezca la bandera para la configuración del proveedor de contenido para activarla nuevamente. |
boolean | runInstrumentationTests (IRemoteAndroidTestRunner runner, ITestLifeCycleReceiver... listeners) Método conveniente para realizar |
boolean | runInstrumentationTests (IRemoteAndroidTestRunner runner, listeners) runInstrumentationTests (IRemoteAndroidTestRunner runner, listeners) Ejecuta pruebas de instrumentación y proporciona recuperación de dispositivos. |
boolean | runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, int userId, listeners) runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, int userId, listeners) Igual que |
boolean | runInstrumentationTestsAsUser (IRemoteAndroidTestRunner runner, int userId, ITestLifeCycleReceiver... listeners) Igual que |
void | setConfiguration ( IConfiguration configuration) Inyecta la |
void | setDate (Date date) Establece la fecha en el dispositivo Nota: la configuración de la fecha en el dispositivo requiere root |
boolean | setDeviceOwner (String componentName, int userId) Establezca un componente de administración del dispositivo como propietario del dispositivo en un usuario determinado. |
void | setDeviceState ( TestDeviceState deviceState) Actualizar el estado del dispositivo. |
void | setEmulatorOutputStream ( SizeLimitedOutputStream output) Para el emulador, configure |
void | setEmulatorProcess (Process p) Establece el |
void | setFastbootEnabled (boolean fastbootEnabled) Configure la opción fastboot para el dispositivo. |
void | setFastbootPath (String fastbootPath) Establece la ruta al binario fastboot que debe usarse. |
void | setIDevice (IDevice newDevice) Actualice el IDevice asociado con este ITestDevice. |
void | setLogStartDelay (int delay) Establece el tiempo de espera en ms antes de iniciar la captura de logcat para un dispositivo en línea. |
void | setOptions ( TestDeviceOptions options) Establezca |
boolean | setProperty (String propKey, String propValue) Establece el valor de propiedad dado en el dispositivo. |
void | setRecovery ( IDeviceRecovery recovery) Configure |
void | setRecoveryMode ( ITestDevice.RecoveryMode mode) Establezca el modo de recuperación actual para usar con el dispositivo. |
void | setSetting (String namespace, String key, String value) Consulte |
void | setSetting (int userId, String namespace, String key, String value) Agregue un valor de configuración al espacio de nombres de un usuario determinado. |
void | setTestLogger ( ITestLogger testLogger) Inyecta la instancia |
void | setUseFastbootErase (boolean useFastbootErase) Establezca si usar el borrado de inicio rápido o el formato de inicio rápido para borrar una partición en el dispositivo. |
void | startLogcat () Comience a capturar la salida logcat del dispositivo en segundo plano. |
boolean | startUser (int userId) Inicia un usuario determinado en segundo plano si actualmente está detenido. |
boolean | startUser (int userId, boolean waitFlag) Inicia un usuario determinado en segundo plano si actualmente está detenido. |
boolean | startVisibleBackgroundUser (int userId, int displayId, boolean waitFlag) Inicia un usuario determinado en segundo plano, visible en la pantalla dada (es decir, permite que el usuario inicie actividades en esa pantalla). |
void | stopEmulatorOutput () Cierre y elimine la salida del emulador. |
void | stopLogcat () Deje de capturar la salida de logcat del dispositivo y deseche los datos de logcat guardados actualmente. |
boolean | stopUser (int userId) Detiene a un usuario determinado. |
boolean | stopUser (int userId, boolean waitFlag, boolean forceFlag) Detener a un usuario determinado. |
String | switchToAdbTcp () Cambie el dispositivo al modo adb-over-tcp. |
boolean | switchToAdbUsb () Cambie el dispositivo a adb en modo usb. |
boolean | switchUser (int userId) Cambie a otro ID de usuario con un tiempo de espera predeterminado. |
boolean | switchUser (int userId, long timeout) Cambie a otro ID de usuario con el tiempo de espera proporcionado como fecha límite. |
boolean | syncFiles (File localFileDir, String deviceFilePath) Sincroniza de forma incremental el contenido de un directorio de archivos local con el dispositivo. |
Bugreport | takeBugreport () Tome un informe de error y devuélvalo dentro de un objeto |
String | uninstallPackage (String packageName) Desinstale un paquete de Android del dispositivo. |
String | uninstallPackageForUser (String packageName, int userId) Desinstale un paquete de Android del dispositivo para un usuario determinado. |
boolean | unlockDevice () Desbloquea el dispositivo si el dispositivo está en un estado cifrado. |
boolean | waitForBootComplete (long timeOut) Bloquea hasta que se establece el indicador de inicio completo del dispositivo. |
boolean | waitForDeviceAvailable () Espera a que el dispositivo responda y esté disponible para la prueba. |
boolean | waitForDeviceAvailable (long waitTime) Espera a que el dispositivo responda y esté disponible para la prueba. |
boolean | waitForDeviceAvailableInRecoverPath (long waitTime) Espera a que el dispositivo responda y esté disponible sin considerar la ruta de recuperación. |
void | waitForDeviceBootloader () Bloquea hasta que el dispositivo sea visible a través de fastboot. |
boolean | waitForDeviceInRecovery (long waitTime) Bloquea para que el dispositivo esté en el estado de 'recuperación de adb' (tenga en cuenta que esto es distinto de |
boolean | waitForDeviceInSideload (long waitTime) Bloqueos para que el dispositivo esté en el estado 'adb sideload' |
boolean | waitForDeviceNotAvailable (long waitTime) Bloques para que el dispositivo no esté disponible, es decir, falta en adb |
void | waitForDeviceOnline () Bloquea hasta que el dispositivo sea visible a través de adb. |
void | waitForDeviceOnline (long waitTime) Bloquea hasta que el dispositivo sea visible a través de adb. |
boolean | waitForDeviceShell (long waitTime) Espera a que el dispositivo responda a un comando básico de adb shell. |
Métodos protegidos | |
---|---|
String[] | buildAdbShellCommand (String command, boolean forceExitStatusDetection) Construye el comando del sistema operativo para la sesión de comandos de adb shell y los argumentos |
void | checkApiLevelAgainst (String feature, int strictMinLevel) |
NativeDevice.RebootDeviceAction | createRebootDeviceAction ( NativeDevice.RebootMode rebootMode, String reason) Cree una |
IRunUtil | createRunUtil () |
void | doAdbReboot ( NativeDevice.RebootMode rebootMode, String reason) Realice un reinicio adb. |
void | ensureRuntimePermissionSupported () método auxiliar para lanzar una excepción si no se admite el permiso de tiempo de ejecución |
int | getApiLevelSafe () |
ITestLogger | getLogger () |
IRunUtil | getRunUtil () Obtenga la instancia |
void | initializeConnection ( IBuildInfo info, MultiMap <String, String> attributes) |
String | internalGetProperty (String propName, String fastbootVar, String description) Obtenga una propiedad del dispositivo, de la memoria caché ddmlib de forma predeterminada, y recurra a `adb shell getprop` o `fastboot getvar` dependiendo de si el dispositivo está en Fastboot o no. |
boolean | isInRebootCallback () Devuelve si las devoluciones de llamada de reinicio se están ejecutando actualmente o no. |
boolean | isNewer (File localFile, IFileEntry entry) Devuelve |
void | notifyRebootEnded () Notifica a todos |
void | notifyRebootStarted () Notifica a todos |
boolean | performDeviceAction (String actionDescription, NativeDevice.DeviceAction action, int retryAttempts) Realiza una acción en este dispositivo. |
void | postAdbReboot () Posibles acciones adicionales que se pueden realizar después de un reinicio. |
void | prePostBootSetup () Permite que cada tipo de dispositivo (AndroidNativeDevice, TestDevice) anule este método para una configuración posterior al arranque específica. |
boolean | pullFileInternal (String remoteFilePath, File localFile) |
void | setClock (Clock clock) Establezca la instancia de Clock para usar. |
void | setMicrodroidProcess (Process process) Marca TestDevice como microdroide y establece su CID. |
void | setTestDeviceOptions ( deviceOptions) setTestDeviceOptions ( deviceOptions) |
CommandResult | simpleFastbootCommand (long timeout, envVarMap, String[] fullCmd) simpleFastbootCommand (long timeout, envVarMap, String[] fullCmd) Ejecuta un comando fastboot simple con variables de entorno e informa el estado del comando. |
CommandResult | simpleFastbootCommand (long timeout, String[] fullCmd) Ejecuta un comando fastboot simple e informa el estado del comando. |
boolean | waitForDeviceNotAvailable (String operationDesc, long time) Espere a que el dispositivo deje de estar disponible (deje de informar a adb). |
constantes
ID DE USUARIO INVALIDO
public static final int INVALID_USER_ID
Valor devuelto para cualquier identificación de usuario no válida/no encontrada: UserHandle definió el 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
el número predeterminado de intentos de reintento de comando para realizar
Valor constante: 2 (0x00000002)
Campos
TARJETA SD
protected static final String SD_CARD
ALMACENAMIENTO_EMULADO
protected static final String STORAGE_EMULATED
mOpciones
protected TestDeviceOptions mOptions
Constructores públicos
Dispositivo nativo
public NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)
Crea un TestDevice
.
Parámetros | |
---|---|
device | IDevice : el IDevice asociado |
stateMonitor | IDeviceStateMonitor : el mecanismo IDeviceStateMonitor para usar |
allocationMonitor | IDeviceMonitor : el IDeviceMonitor para informar de los cambios de estado de asignación. puede ser nulo |
Métodos públicos
canSwitchToHeadlessSystemUser
public boolean canSwitchToHeadlessSystemUser ()
Devuelve si está permitido cambiar al usuario del SISTEMA sin cabeza.
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
DeviceNotAvailableException |
comprobarApiLevelAgainstNextRelease
public boolean checkApiLevelAgainstNextRelease (int strictMinLevel)
Compruebe si una función es compatible actualmente o no dado un nivel mínimo compatible. Este método tiene en cuenta funciones inéditas aún, antes de que se eleve el nivel de la API.
Parámetros | |
---|---|
strictMinLevel | int : el nivel posible mínimo estricto que admite la característica. |
Devoluciones | |
---|---|
boolean | True si el nivel es compatible. Falso en caso contrario. |
Lanza | |
---|---|
DeviceNotAvailableException |
checkConectividad
public boolean checkConnectivity ()
Compruebe que el dispositivo tiene conectividad de red.
Devoluciones | |
---|---|
boolean | true si el dispositivo tiene una conexión de red en funcionamiento, false en caso contrario. |
Lanza | |
---|---|
DeviceNotAvailableException |
borrar diálogos de error
public boolean clearErrorDialogs ()
Intente descartar los cuadros de diálogo de error que se muestran actualmente en la interfaz de usuario del dispositivo.
Devoluciones | |
---|---|
boolean | true si no había cuadros de diálogo o los cuadros de diálogo se borraron correctamente. false en caso contrario. |
Lanza | |
---|---|
DeviceNotAvailableException |
clearLastConnectedWifiNetwork
public void clearLastConnectedWifiNetwork ()
Borra la última red wifi conectada. Esto debe llamarse al iniciar una nueva invocación para evitar conectarse a la red wifi utilizada en la prueba anterior después de que se reinicie el dispositivo.
borrarLogcat
public void clearLogcat ()
Elimina cualquier dato logcat acumulado.
Esto es útil para los casos en los que desea asegurarse de queITestDevice#getLogcat()
solo devuelva los datos de registro producidos después de cierto punto (como después de actualizar una nueva versión del dispositivo, etc.). conectarse a la red Wi-Fi
public boolean connectToWifiNetwork (wifiSsidToPsk, boolean scanSsid)
Se conecta a una red wifi.
Enciende wifi y bloquea hasta que se establece una conexión exitosa con una de las redes wifi proporcionadas en el mapa wifiSsidToPsk. Una vez que se establece una conexión, la instancia intentará restaurar la conexión después de cada reinicio hasta que se llame a ITestDevice#disconnectFromWifi()
o ITestDevice#clearLastConnectedWifiNetwork()
.
Parámetros | |
---|---|
wifiSsidToPsk | |
scanSsid | boolean : si buscar SSID ocultos para esta red. |
Devoluciones | |
---|---|
boolean | true si está conectado a la red wifi con éxito. false de lo contrario |
Lanza | |
---|---|
DeviceNotAvailableException |
conectarse a la red Wi-Fi
public boolean connectToWifiNetwork (String wifiSsid, String wifiPsk)
Se conecta a una red wifi.
Enciende wifi y bloquea hasta que se establece una conexión exitosa a la red wifi especificada. Una vez que se establece una conexión, la instancia intentará restaurar la conexión después de cada reinicio hasta que se llame aITestDevice#disconnectFromWifi()
o ITestDevice#clearLastConnectedWifiNetwork()
.Parámetros | |
---|---|
wifiSsid | String : el ssid wifi para conectarse |
wifiPsk | String : frase de contraseña de PSK o nula si no está cifrada |
Devoluciones | |
---|---|
boolean | true si está conectado a la red wifi con éxito. false de lo contrario |
Lanza | |
---|---|
DeviceNotAvailableException |
conectarse a la red Wi-Fi
public boolean connectToWifiNetwork (wifiSsidToPsk)
Se conecta a una red wifi.
Enciende wifi y bloquea hasta que se establece una conexión exitosa con una de las redes wifi proporcionadas en el mapa wifiSsidToPsk. Una vez que se establece una conexión, la instancia intentará restaurar la conexión después de cada reinicio hasta que se llame a ITestDevice#disconnectFromWifi()
o ITestDevice#clearLastConnectedWifiNetwork()
Parámetros | |
---|---|
wifiSsidToPsk |
Devoluciones | |
---|---|
boolean | true si está conectado a la red wifi con éxito. false de lo contrario |
Lanza | |
---|---|
DeviceNotAvailableException |
conectarse a la red Wi-Fi
public boolean connectToWifiNetwork (String wifiSsid, String wifiPsk, boolean scanSsid)
Se conecta a una red wifi.
Enciende wifi y bloquea hasta que se establece una conexión exitosa a la red wifi especificada. Una vez que se establece una conexión, la instancia intentará restaurar la conexión después de cada reinicio hasta que se llame aITestDevice#disconnectFromWifi()
o ITestDevice#clearLastConnectedWifiNetwork()
.Parámetros | |
---|---|
wifiSsid | String : el ssid wifi para conectarse |
wifiPsk | String : frase de contraseña de PSK o nula si no está cifrada |
scanSsid | boolean : si buscar SSID oculto para esta red. |
Devoluciones | |
---|---|
boolean | true si está conectado a la red wifi con éxito. false de lo contrario |
Lanza | |
---|---|
DeviceNotAvailableException |
connectToWifiNetworkIfNeeded
public boolean connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk, boolean scanSsid)
Una variante de connectToWifiNetwork(String, String)
que solo se conecta si el dispositivo actualmente no tiene conectividad de red.
Parámetros | |
---|---|
scanSsid | boolean : si buscar SSID oculto para esta red |
Devoluciones | |
---|---|
boolean | true si está conectado a la red wifi con éxito. false de lo contrario |
Lanza | |
---|---|
DeviceNotAvailableException |
connectToWifiNetworkIfNeeded
public boolean connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk)
Una variante de connectToWifiNetwork(String, String)
que solo se conecta si el dispositivo actualmente no tiene conectividad de red.
Devoluciones | |
---|---|
boolean | true si está conectado a la red wifi con éxito. false de lo contrario |
Lanza | |
---|---|
DeviceNotAvailableException |
crear usuario
public int createUser (String name, boolean guest, boolean ephemeral)
Cree un usuario con un nombre dado y las banderas proporcionadas
Parámetros | |
---|---|
name | String : del usuario a crear en el dispositivo |
guest | boolean : habilita la marca de usuario --guest durante la creación |
ephemeral | boolean : habilitar el indicador de usuario --efímero durante la creación |
Devoluciones | |
---|---|
int | id del usuario creado |
Lanza | |
---|---|
DeviceNotAvailableException |
crear usuario
public int createUser (String name, boolean guest, boolean ephemeral, boolean forTesting)
Cree un usuario con un nombre dado y las banderas proporcionadas
Parámetros | |
---|---|
name | String : del usuario a crear en el dispositivo |
guest | boolean : habilita la marca de usuario --guest durante la creación |
ephemeral | boolean : habilitar el indicador de usuario --efímero durante la creación |
forTesting | boolean : habilita el indicador de prueba --para probar durante la creación |
Devoluciones | |
---|---|
int | id del usuario creado |
Lanza | |
---|---|
DeviceNotAvailableException |
crear usuario
public int createUser (String name)
Cree un usuario con un nombre dado y banderas predeterminadas 0.
Parámetros | |
---|---|
name | String : del usuario a crear en el dispositivo |
Devoluciones | |
---|---|
int | el número entero para la identificación de usuario creada |
Lanza | |
---|---|
DeviceNotAvailableException |
crearUsuarioNoLanzar
public int createUserNoThrow (String name)
Cree un usuario con un nombre dado y banderas predeterminadas 0.
Parámetros | |
---|---|
name | String : del usuario a crear en el dispositivo |
Devoluciones | |
---|---|
int | el número entero para el ID de usuario creado o -1 para el error. |
Lanza | |
---|---|
DeviceNotAvailableException |
borrar archivo
public void deleteFile (String deviceFilePath)
Método auxiliar para eliminar un archivo o directorio en el dispositivo.
Parámetros | |
---|---|
deviceFilePath | String : la ruta absoluta del archivo en el dispositivo. |
Lanza | |
---|---|
DeviceNotAvailableException |
deregisterDeviceActionReceiver
public void deregisterDeviceActionReceiver (IDeviceActionReceiver deviceActionReceiver)
Elimina el IDeviceActionReceiver
registrado.
Parámetros | |
---|---|
deviceActionReceiver | IDeviceActionReceiver : un IDeviceActionReceiver que se eliminará. |
dispositivoSoftRestarted
public boolean deviceSoftRestarted (ProcessInfo prevSystemServerProcess)
Método de ayuda para verificar si el dispositivo se reinició por software al comparar system_server actual con system_server ProcessInfo
anterior. Use getProcessByName(String)
para obtener ProcessInfo
.
Parámetros | |
---|---|
prevSystemServerProcess | ProcessInfo : el proceso system_server anterior ProcessInfo . |
Devoluciones | |
---|---|
boolean | true si el dispositivo se reinicia suavemente |
Lanza | |
---|---|
DeviceNotAvailableException |
dispositivoSoftRestartedDesde
public boolean deviceSoftRestartedSince (long utcEpochTime, TimeUnit timeUnit)
Método auxiliar para comprobar si el dispositivo se reinició desde la hora UTC desde la época del dispositivo y su ERROR(/TimeUnit)
. Soft-Restart se refiere a system_server reiniciado fuera de un reinicio completo del dispositivo (por ejemplo: reinicio solicitado). El dispositivo actual utcEpochTime en Milliseccond se puede obtener mediante el método getDeviceDate()
.
Parámetros | |
---|---|
utcEpochTime | long : el tiempo del dispositivo en segundos desde la época. |
timeUnit | TimeUnit : la unidad de tiempo TimeUnit para el utcEpochTime dado. |
Devoluciones | |
---|---|
boolean | true si el dispositivo se reinicia suavemente |
Lanza | |
---|---|
DeviceNotAvailableException |
deshabilitarAdbRoot
public boolean disableAdbRoot ()
Desactiva adb root.
Deshabilitar adb root puede hacer que el dispositivo se desconecte de adb. Este método se bloqueará hasta que el dispositivo esté disponible.Devoluciones | |
---|---|
boolean | true si tiene éxito. |
Lanza | |
---|---|
DeviceNotAvailableException |
desactivar Keyguard
public void disableKeyguard ()
Intenta desactivar el bloqueo del teclado.
Primero espere a que el envío de entrada esté listo, esto sucede casi al mismo tiempo cuando el dispositivo informa BOOT_COMPLETE, aparentemente de forma asíncrona, porque la implementación del marco actual tiene una condición de carrera ocasional. Luego se envía el comando para descartar el bloqueo del teclado (solo funciona en los que no son seguros)
Lanza | |
---|---|
DeviceNotAvailableException |
deshabilitar NetworkMonitor
public boolean disableNetworkMonitor ()
Desactiva la supervisión de la red en el dispositivo.
Devoluciones | |
---|---|
boolean | true si la supervisión se deshabilita correctamente. false si falla. |
Lanza | |
---|---|
DeviceNotAvailableException |
desconectar de wifi
public boolean disconnectFromWifi ()
Se desconecta de una red wifi.
Elimina todas las redes de la lista de redes conocidas y desactiva wifi.Devoluciones | |
---|---|
boolean | true si se desconecta de la red wifi con éxito. false si falla la desconexión. |
Lanza | |
---|---|
DeviceNotAvailableException |
existe el archivo
public boolean doesFileExist (String deviceFilePath, int userId)
Método auxiliar para determinar si existe un archivo en el dispositivo para un usuario determinado.
Parámetros | |
---|---|
deviceFilePath | String : la ruta absoluta del archivo en el dispositivo para verificar |
userId | int : la identificación de usuario contra la cual verificar la existencia del archivo |
Devoluciones | |
---|---|
boolean | true si el archivo existe, false en caso contrario. |
Lanza | |
---|---|
DeviceNotAvailableException |
existe el archivo
public boolean doesFileExist (String deviceFilePath)
Método auxiliar para determinar si existe un archivo en el dispositivo.
Parámetros | |
---|---|
deviceFilePath | String : la ruta absoluta del archivo en el dispositivo para verificar |
Devoluciones | |
---|---|
boolean | true si el archivo existe, false en caso contrario. |
Lanza | |
---|---|
DeviceNotAvailableException |
basurero
public File dumpHeap (String process, String devicePath)
Intente volcar el montón de system_server. Es responsabilidad de la persona que llama limpiar el archivo volcado.
Parámetros | |
---|---|
process | String : el nombre del proceso del dispositivo en el que se va a realizar el volcado. |
devicePath | String : la ruta en el dispositivo donde colocar el volcado. Esta debe ser una ubicación donde los permisos lo permitan. |
Devoluciones | |
---|---|
File | el ERROR(/File) que contiene el informe. Nulo si algo falla. |
Lanza | |
---|---|
DeviceNotAvailableException |
habilitarAdbRoot
public boolean enableAdbRoot ()
Activa adb root. Si la configuración "habilitar raíz" es "falsa", registrará un mensaje y regresará sin habilitar la raíz.
Habilitar adb root puede hacer que el dispositivo se desconecte de adb. Este método se bloqueará hasta que el dispositivo esté disponible.Devoluciones | |
---|---|
boolean | true si tiene éxito. |
Lanza | |
---|---|
DeviceNotAvailableException |
habilitarNetworkMonitor
public boolean enableNetworkMonitor ()
Habilita el monitoreo de la red en el dispositivo.
Devoluciones | |
---|---|
boolean | true si la supervisión se habilita correctamente. false si falla. |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarAdbCommand
public String executeAdbCommand (long timeout, String... cmdArgs)
Método auxiliar que ejecuta un comando adb como un comando del sistema con un tiempo de espera especificado.
En su lugar, se debe usar executeShellCommand(String)
siempre que sea posible, ya que ese método proporciona una mejor detección de fallas y rendimiento.
Parámetros | |
---|---|
timeout | long : el tiempo en milisegundos antes de que el dispositivo se considere que no responde, 0L para ningún tiempo de espera |
cmdArgs | String : el comando adb y los argumentos para ejecutar |
Devoluciones | |
---|---|
String | la salida estándar del comando. null si el comando no se pudo ejecutar. |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarAdbCommand
public String executeAdbCommand (long timeout,envMap, String... cmdArgs)
Método auxiliar que ejecuta un comando adb como un comando del sistema con un tiempo de espera especificado.
En su lugar, se debe usar executeShellCommand(String)
siempre que sea posible, ya que ese método proporciona una mejor detección de fallas y rendimiento.
Parámetros | |
---|---|
timeout | long : el tiempo en milisegundos antes de que el dispositivo se considere que no responde, 0L para ningún tiempo de espera |
envMap | |
cmdArgs | String : el comando adb y los argumentos para ejecutar |
Devoluciones | |
---|---|
String | la salida estándar del comando. null si el comando no se pudo ejecutar. |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarAdbCommand
public String executeAdbCommand (String... cmdArgs)
Método auxiliar que ejecuta un comando adb como un comando del sistema.
En su lugar, se debe usarexecuteShellCommand(String)
siempre que sea posible, ya que ese método proporciona una mejor detección de fallas y rendimiento.Parámetros | |
---|---|
cmdArgs | String : el comando adb y los argumentos para ejecutar |
Devoluciones | |
---|---|
String | la salida estándar del comando. null si el comando no se pudo ejecutar. |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarFastbootCommand
public CommandResult executeFastbootCommand (String... cmdArgs)
Método auxiliar que ejecuta un comando fastboot como un comando del sistema con un tiempo de espera predeterminado de 2 minutos.
Se espera que se use cuando el dispositivo ya está en modo fastboot.
Parámetros | |
---|---|
cmdArgs | String : el comando fastboot y los argumentos para ejecutar |
Devoluciones | |
---|---|
CommandResult | el CommandResult que contiene la salida del comando |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarFastbootCommand
public CommandResult executeFastbootCommand (long timeout, String... cmdArgs)
Método auxiliar que ejecuta un comando fastboot como un comando del sistema.
Se espera que se use cuando el dispositivo ya está en modo fastboot.Parámetros | |
---|---|
timeout | long : el tiempo en milisegundos antes de que caduque el comando |
cmdArgs | String : el comando fastboot y los argumentos para ejecutar |
Devoluciones | |
---|---|
CommandResult | el CommandResult que contiene la salida del comando |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarLongFastbootCommand
public CommandResult executeLongFastbootCommand (String... cmdArgs)
Método auxiliar que ejecuta un comando fastboot de ejecución prolongada como un comando del sistema.
Idéntico aexecuteFastbootCommand(String)
excepto que usa un tiempo de espera más largo.Parámetros | |
---|---|
cmdArgs | String : el comando fastboot y los argumentos para ejecutar |
Devoluciones | |
---|---|
CommandResult | el CommandResult que contiene la salida del comando |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarLongFastbootCommand
public CommandResult executeLongFastbootCommand (envVarMap, String... cmdArgs)
Método auxiliar que ejecuta un comando fastboot de ejecución prolongada como un comando del sistema con variables de entorno del sistema.
Idéntico a executeFastbootCommand(String)
excepto que usa un tiempo de espera más largo.
Parámetros | |
---|---|
envVarMap | |
cmdArgs | String : el comando fastboot y los argumentos para ejecutar |
Devoluciones | |
---|---|
CommandResult | el CommandResult que contiene la salida del comando |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarShellCommand
public String executeShellCommand (String command)
Método auxiliar que ejecuta un comando adb shell y devuelve el resultado como ERROR(/String)
.
Parámetros | |
---|---|
command | String : el comando adb shell para ejecutar |
Devoluciones | |
---|---|
String | la salida de la cáscara |
Lanza | |
---|---|
DeviceNotAvailableException |
ejecutarShellCommand
public void executeShellCommand (String command, IShellOutputReceiver receiver, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)
Ejecuta un comando de shell adb, con más parámetros para controlar el comportamiento del comando.
Parámetros | |
---|---|
command | String : el comando adb shell para ejecutar |
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. |
Lanza | |
---|---|
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. |
Lanza | |
---|---|
DeviceNotAvailableException |
executeShellCommand
public void executeShellCommand (String command, IShellOutputReceiver receiver)
Executes the given adb shell command, retrying multiple times if command fails.
A simpler form ofexecuteShellCommand(String, 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. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
CommandResult | The result in CommandResult . |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
CommandResult | The result in CommandResult . |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
CommandResult | The result in CommandResult . |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
CommandResult |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
CommandResult |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
CommandResult |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
CommandResult |
Lanza | |
---|---|
DeviceNotAvailableException |
fastbootWipePartition
public CommandResult fastbootWipePartition (String partition)
Helper method which wipes a partition for the device.
IfgetUseFastbootErase()
is true
, then fastboot erase will be used to wipe the partition. The device must then create a filesystem the next time the device boots. Otherwise, fastboot format is used which will create a new filesystem on the device. Expected to be used when device is already in fastboot mode.Parámetros | |
---|---|
partition | String : the partition to wipe |
Devoluciones | |
---|---|
CommandResult | the CommandResult containing output of command |
Lanza | |
---|---|
DeviceNotAvailableException |
getActiveApexes
publicgetActiveApexes ()
Fetch the information about APEXes activated on the device.
Devoluciones | |
---|---|
ERROR(/Set) of ApexInfo currently activated on the device |
Lanza | |
---|---|
DeviceNotAvailableException |
getAllSettings
publicgetAllSettings (String namespace)
Return key value pairs of requested namespace.
Parámetros | |
---|---|
namespace | String : must be one of {"system", "secure", "global"} |
Devoluciones | |
---|---|
the map of key value pairs. Null if namespace is not supported. |
Lanza | |
---|---|
DeviceNotAvailableException |
getAllocationState
public DeviceAllocationState getAllocationState ()
Return the current allocation state of device
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
String |
Lanza | |
---|---|
DeviceNotAvailableException |
getAndroidIds
publicgetAndroidIds ()
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.
Devoluciones | |
---|---|
Map of android ids found matching user ids. |
Lanza | |
---|---|
DeviceNotAvailableException |
getApiLevel
public int getApiLevel ()
Get the device API Level. Defaults to UNKNOWN_API_LEVEL
.
Devoluciones | |
---|---|
int | an integer indicating the API Level of device |
Lanza | |
---|---|
DeviceNotAvailableException |
getAppPackageInfo
public PackageInfo getAppPackageInfo (String packageName)
Fetch information about a package installed on device.
Parámetros | |
---|---|
packageName | String |
Devoluciones | |
---|---|
PackageInfo | the PackageInfo or null if information could not be retrieved |
Lanza | |
---|---|
DeviceNotAvailableException |
getAppPackageInfos
publicgetAppPackageInfos ()
Fetch information of packages installed on the device.
Devoluciones | |
---|---|
ERROR(/List) of PackageInfo s installed on the device. |
Lanza | |
---|---|
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
.
Devoluciones | |
---|---|
String | the ERROR(/String) baseband version or null if it cannot be determined (device has no radio or version string cannot be read) |
Lanza | |
---|---|
DeviceNotAvailableException |
getBattery
public Integer getBattery ()
Returns the current battery level of a device or Null if battery level unavailable.
Devoluciones | |
---|---|
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. |
Devoluciones | |
---|---|
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. |
Lanza | |
---|---|
DeviceNotAvailableException |
getBootHistory
publicgetBootHistory ()
Helper method collects the boot history map with boot time and boot reason.
Devoluciones | |
---|---|
Map of boot time (UTC time in second since Epoch) and boot reason |
Lanza | |
---|---|
DeviceNotAvailableException |
getBootHistorySince
publicgetBootHistorySince (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 . |
Devoluciones | |
---|---|
Map of boot time (UTC time in second since Epoch) and boot reason |
Lanza | |
---|---|
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)Devoluciones | |
---|---|
String | the ERROR(/String) bootloader version or null if it cannot be found |
Lanza | |
---|---|
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).
Devoluciones | |
---|---|
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
Devoluciones | |
---|---|
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
Devoluciones | |
---|---|
String | the build alias or fall back to build id if it could not be retrieved |
Lanza | |
---|---|
DeviceNotAvailableException |
getBuildFlavor
public String getBuildFlavor ()
Retrieve the build flavor for the device.
Devoluciones | |
---|---|
String | the build flavor or null if it could not be retrieved |
Lanza | |
---|---|
DeviceNotAvailableException |
getBuildId
public String getBuildId ()
Retrieve the build the device is currently running.
Devoluciones | |
---|---|
String | the build id or IBuildInfo#UNKNOWN_BUILD_ID if it could not be retrieved |
Lanza | |
---|---|
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)
Devoluciones | |
---|---|
String | The signing key if found, null otherwise. |
Lanza | |
---|---|
DeviceNotAvailableException |
getCachedDeviceDescriptor
public DeviceDescriptor getCachedDeviceDescriptor ()
Returns a cached DeviceDescriptor
if the device is allocated, otherwise returns the current DeviceDescriptor
.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
String[] | Array of string containing all the file in a path on the device. |
Lanza | |
---|---|
DeviceNotAvailableException |
getConnection
public AbstractConnection getConnection ()
The current connection associated with the device.
Devoluciones | |
---|---|
AbstractConnection |
getCurrentFoldableState
public DeviceFoldableState getCurrentFoldableState ()
Returns the current foldable state of the device or null if some issues occurred.
Devoluciones | |
---|---|
DeviceFoldableState |
Lanza | |
---|---|
DeviceNotAvailableException |
getCurrentUser
public int getCurrentUser ()
Return the id of the current running user. In case of error, return -10000.
Devoluciones | |
---|---|
int |
Lanza | |
---|---|
DeviceNotAvailableException |
getDeviceClass
public String getDeviceClass ()
Get the device class.
Devoluciones | |
---|---|
String | the ERROR(/String) device class. |
getDeviceDate
public long getDeviceDate ()
Return the date of the device in millisecond since epoch.
Devoluciones | |
---|---|
long | the date of the device in epoch format. |
Lanza | |
---|---|
DeviceNotAvailableException |
getDeviceDescriptor
public DeviceDescriptor getDeviceDescriptor ()
Return a DeviceDescriptor
from the device information to get info on it without passing the actual device object.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
DeviceDescriptor |
getDeviceState
public TestDeviceState getDeviceState ()
Get the device's state.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
long | the difference in milliseconds |
Lanza | |
---|---|
DeviceNotAvailableException |
getEmulatorOutput
public InputStreamSource getEmulatorOutput ()
Get the stream of emulator stdout and stderr
Devoluciones | |
---|---|
InputStreamSource | emulator output |
getEmulatorProcess
public Process getEmulatorProcess ()
Return the ERROR(/Process)
corresponding to this emulator.
Devoluciones | |
---|---|
Process | the ERROR(/Process) or null |
getExecuteShellCommandLog
public final File getExecuteShellCommandLog ()
The log that contains all the executeShellCommand(String)
logs.
Devoluciones | |
---|---|
File |
getExternalStoreFreeSpace
public long getExternalStoreFreeSpace ()
Helper method to determine amount of free space on device external storage.
Devoluciones | |
---|---|
long | the amount of free space in KB |
Lanza | |
---|---|
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.
Devoluciones | |
---|---|
String |
getFastbootProductType
public String getFastbootProductType ()
Convenience method to get the product type of this device when its in fastboot mode.
This method should only be used if device should be in fastboot. Its a bit safer variant than the genericgetProductType()
method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.Devoluciones | |
---|---|
String | the ERROR(/String) product type name or null if it cannot be determined |
Lanza | |
---|---|
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 genericgetProductType()
method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.Devoluciones | |
---|---|
String | the ERROR(/String) product type name or null if it cannot be determined |
Lanza | |
---|---|
DeviceNotAvailableException |
getFastbootSerialNumber
public String getFastbootSerialNumber ()
Returns the fastboot mode serial number.
Devoluciones | |
---|---|
String |
getFastbootVariable
public String getFastbootVariable (String variableName)
Retrieve the given fastboot variable value from the device.
Parámetros | |
---|---|
variableName | String : the variable name |
Devoluciones | |
---|---|
String | the property value or null if it does not exist |
Lanza | |
---|---|
DeviceNotAvailableException |
getFastbootVersion
public String getFastbootVersion ()
Returns the version string of the fastboot binary being used. Or null if something goes wrong.
Devoluciones | |
---|---|
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) |
Devoluciones | |
---|---|
IFileEntry | the IFileEntry or null if file at given path cannot be found |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
IFileEntry | a FileEntryWrapper representing the FileEntry. |
Lanza | |
---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException |
getFoldableStates
publicgetFoldableStates ()
Returns the list of foldable states on the device. Can be obtained with "cmd device_state print-states".
Devoluciones | |
---|---|
Lanza | |
---|---|
DeviceNotAvailableException |
getIDevice
public IDevice getIDevice ()
Returns a reference to the associated ddmlib IDevice
.
IDevice
may be allocated by DDMS each time the device disconnects and reconnects from adb. Thus callers should not keep a reference to the IDevice
, because that reference may become stale.Devoluciones | |
---|---|
IDevice | the IDevice |
getInstalledPackageNames
publicgetInstalledPackageNames ()
Fetch the application package names present on the device.
Devoluciones | |
---|---|
ERROR(/Set) of ERROR(/String) package names currently installed on the device. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
long | the property value or defaultValue if the property is empty, doesn't exist, or doesn't have an integer value. |
Lanza | |
---|---|
DeviceNotAvailableException |
getIpAddress
public String getIpAddress ()
Gets the device's IP address.
Devoluciones | |
---|---|
String | the device's IP address, or null if device has no IP address |
Lanza | |
---|---|
DeviceNotAvailableException |
getKeyguardState
public KeyguardControllerState getKeyguardState ()
Return an object to get the current state of the keyguard or null if not supported.
Devoluciones | |
---|---|
KeyguardControllerState | a KeyguardControllerState containing a snapshot of the state of the keyguard and returns Null if the Keyguard query is not supported. |
Lanza | |
---|---|
DeviceNotAvailableException |
getLastExpectedRebootTimeMillis
public long getLastExpectedRebootTimeMillis ()
Returns the last time Tradefed APIs triggered a reboot in milliseconds since EPOCH as returned by ERROR(/System#currentTimeMillis())
.
Devoluciones | |
---|---|
long |
getLaunchApiLevel
public int getLaunchApiLevel ()
Get the device's first launched API Level. Defaults to UNKNOWN_API_LEVEL
.
Devoluciones | |
---|---|
int | an integer indicating the first launched API Level of device |
Lanza | |
---|---|
DeviceNotAvailableException |
getLogcat
public InputStreamSource getLogcat ()
Grabs a snapshot stream of the logcat data.
Works in two modes:
TestDeviceOptions.getMaxLogcatDataSize()
bytes of the current contents of the background logcat captureDevoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
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.
Devoluciones | |
---|---|
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') |
Devoluciones | |
---|---|
InputStreamSource |
getMacAddress
public String getMacAddress ()
Returns the MAC address of the device, null if it fails to query from the device.
Devoluciones | |
---|---|
String |
getMainUserId
public Integer getMainUserId ()
Returns the main user id.
Devoluciones | |
---|---|
Integer | the userId of the main user if there is one, and null if there is no main user. |
Lanza | |
---|---|
DeviceNotAvailableException |
getMainlineModuleInfo
publicgetMainlineModuleInfo ()
Get the information about the mainline modules installed on the device.
Devoluciones | |
---|---|
ERROR(/Set) of ERROR(/String) mainline modules currently installed on the device. |
Lanza | |
---|---|
DeviceNotAvailableException |
getMaxNumberOfRunningUsersSupported
public int getMaxNumberOfRunningUsersSupported ()
Get the maximum number of supported simultaneously running users. Defaults to 0.
Devoluciones | |
---|---|
int | an integer indicating the number of simultaneously running users |
Lanza | |
---|---|
DeviceNotAvailableException |
getMaxNumberOfUsersSupported
public int getMaxNumberOfUsersSupported ()
Get the maximum number of supported users. Defaults to 0.
Devoluciones | |
---|---|
int | an integer indicating the number of supported users |
Lanza | |
---|---|
DeviceNotAvailableException |
getMicrodroidProcess
public Process getMicrodroidProcess ()
Devoluciones | |
---|---|
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.
Devoluciones | |
---|---|
IDeviceStateMonitor |
getMountPoint
public String getMountPoint (String mountName)
Returns a mount point.
Queries the device directly if the cached info inIDevice
is not available. TODO: move this behavior to IDevice#getMountPoint(String)
Parámetros | |
---|---|
mountName | String : the name of the mount point |
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
ITestDevice.MountPointInfo | A ERROR(/List) of MountPointInfo containing the information in "/proc/mounts" |
Lanza | |
---|---|
DeviceNotAvailableException |
getMountPointInfo
publicgetMountPointInfo ()
Returns a parsed version of the information in /proc/mounts on the device
Devoluciones | |
---|---|
A ERROR(/List) of MountPointInfo containing the information in "/proc/mounts" |
Lanza | |
---|---|
DeviceNotAvailableException |
getOptions
public TestDeviceOptions getOptions ()
Fetch the test options for the device.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
long | the amount of free space in KB |
Lanza | |
---|---|
DeviceNotAvailableException |
getPrimaryUserId
public Integer getPrimaryUserId ()
Returns the primary user id.
Devoluciones | |
---|---|
Integer | the userId of the primary user if there is one, and null if there is no primary user. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
ProcessInfo | ProcessInfo of given processName |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String |
Lanza | |
---|---|
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.Devoluciones | |
---|---|
String | the ERROR(/String) product type name. Will not be null |
Lanza | |
---|---|
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.Devoluciones | |
---|---|
String | the ERROR(/String) product variant name or null if it cannot be determined |
Lanza | |
---|---|
DeviceNotAvailableException |
getProperty
public String getProperty (String name)
Retrieve the given property value from the device.
Parámetros | |
---|---|
name | String : the property name |
Devoluciones | |
---|---|
String | the property value or null if it does not exist |
Lanza | |
---|---|
DeviceNotAvailableException |
getRecoveryMode
public ITestDevice.RecoveryMode getRecoveryMode ()
Get the current recovery mode used for the device.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
InputStreamSource | a InputStreamSource of the screenshot in format, or null if the screenshot was not successful. |
Lanza | |
---|---|
DeviceNotAvailableException |
getScreenshot
public InputStreamSource getScreenshot ()
Grabs a screenshot from the device.
Devoluciones | |
---|---|
InputStreamSource | a InputStreamSource of the screenshot in png format, or null if the screenshot was not successful. |
Lanza | |
---|---|
DeviceNotAvailableException |
getSerialNumber
public String getSerialNumber ()
Convenience method to get serial number of this device.
Devoluciones | |
---|---|
String | the ERROR(/String) serial number |
getSetting
public String getSetting (int userId, String namespace, String key)
Return the value of the requested setting. namespace must be one of: {"system", "secure", "global"}
Parámetros | |
---|---|
userId | int |
namespace | String |
key | String |
Devoluciones | |
---|---|
String | the value associated with the namespace:key of a user. Null if not found. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
String |
Lanza | |
---|---|
DeviceNotAvailableException |
getSimOperator
public String getSimOperator ()
Return the SIM card operator or null if not available or if device is not available.
Devoluciones | |
---|---|
String |
getSimState
public String getSimState ()
Return the SIM card state or null if not available or device is not available.
Devoluciones | |
---|---|
String |
getTombstones
publicgetTombstones ()
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.
Devoluciones | |
---|---|
A list of tombstone files, empty if no tombstone. |
Lanza | |
---|---|
DeviceNotAvailableException |
getTotalMemory
public long getTotalMemory ()
Returns total physical memory size in bytes or -1 in case of internal error
Devoluciones | |
---|---|
long |
getUninstallablePackageNames
publicgetUninstallablePackageNames ()
Fetch the application package names that can be uninstalled. This is presently defined as non-system packages, and updated system packages.
Devoluciones | |
---|---|
ERROR(/Set) of uninstallable ERROR(/String) package names currently installed on the device. |
Lanza | |
---|---|
DeviceNotAvailableException |
getUseFastbootErase
public boolean getUseFastbootErase ()
Get whether to use fastboot erase or fastboot format to wipe a partition on the device.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
int | the flags associated with the userId provided if found, -10000 in any other cases. |
Lanza | |
---|---|
DeviceNotAvailableException |
getUserInfos
publicgetUserInfos ()
Gets the Map of useId to UserInfo
on the device. Will throw DeviceRuntimeException
if output from device is not as expected.
Devoluciones | |
---|---|
the list of UserInfo objects. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
int |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
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: |
Devoluciones | |
---|---|
boolean | True if feature is found, false otherwise. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | a ERROR(/String) with an error code, or null if success. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | a ERROR(/String) with an error code, or null if success. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | a ERROR(/String) with an error code, or null if success. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | a ERROR(/String) with an error code, or null if success. |
Lanza | |
---|---|
DeviceNotAvailableException |
isAdbTcp
public boolean isAdbTcp ()
Devoluciones | |
---|---|
boolean |
isAppEnumerationSupported
public boolean isAppEnumerationSupported ()
Check whether platform on device supports app enumeration
Devoluciones | |
---|---|
boolean | True if app enumeration is supported, false otherwise |
Lanza | |
---|---|
DeviceNotAvailableException |
isBypassLowTargetSdkBlockSupported
public boolean isBypassLowTargetSdkBlockSupported ()
Check whether platform on device supports bypassing low target sdk block on app installs
Devoluciones | |
---|---|
boolean | True if bypass low target sdk block is supported, false otherwise |
Lanza | |
---|---|
DeviceNotAvailableException |
isDeviceEncrypted
public boolean isDeviceEncrypted ()
Returns if the device is encrypted.
Devoluciones | |
---|---|
boolean | true if the device is encrypted. |
Lanza | |
---|---|
DeviceNotAvailableException |
isDirectory
public boolean isDirectory (String path)
Return True if the path on the device is a directory, false otherwise.
Parámetros | |
---|---|
path | String |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
DeviceNotAvailableException |
isEnableAdbRoot
public boolean isEnableAdbRoot ()
Devoluciones | |
---|---|
boolean | true if adb root should be enabled on device |
isEncryptionSupported
public boolean isEncryptionSupported ()
Returns if encryption is supported on the device.
Devoluciones | |
---|---|
boolean | true if the device supports encryption. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
DeviceNotAvailableException |
isFastbootEnabled
public boolean isFastbootEnabled ()
Return if fastboot is available for the device.
Devoluciones | |
---|---|
boolean |
isHeadless
public boolean isHeadless ()
Return true if the device is headless (no screen), false otherwise.
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
DeviceNotAvailableException |
isHeadlessSystemUserMode
public boolean isHeadlessSystemUserMode ()
Returns whether the device uses headless system user mode.
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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.
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
DeviceNotAvailableException |
isMultiUserSupported
public boolean isMultiUserSupported ()
Determines if multi user is supported.
Devoluciones | |
---|---|
boolean | true if multi user is supported, false otherwise |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | True if the package is reported as installed. False otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | True if the package is reported as installed. False otherwise. |
Lanza | |
---|---|
DeviceNotAvailableException |
isRuntimePermissionSupported
public boolean isRuntimePermissionSupported ()
Check whether platform on device supports runtime permission granting
Devoluciones | |
---|---|
boolean | True if runtime permission are supported, false otherwise. |
Lanza | |
---|---|
DeviceNotAvailableException |
isStateBootloaderOrFastbootd
public boolean isStateBootloaderOrFastbootd ()
Returns true if device is in TestDeviceState#FASTBOOT
or TestDeviceState.FASTBOOTD
.
Devoluciones | |
---|---|
boolean |
isUserRunning
public boolean isUserRunning (int userId)
Check if a given user is running.
Parámetros | |
---|---|
userId | int |
Devoluciones | |
---|---|
boolean | True if the user is running, false in every other cases. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if the user is secondary, false otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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)
).
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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()
.
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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.Devoluciones | |
---|---|
boolean | true if wifi is enabled. false if disabled |
Lanza | |
---|---|
DeviceNotAvailableException |
listDisplayIds
publiclistDisplayIds ()
Collect the list of available displays id on the device as reported by "dumpsys SurfaceFlinger".
Devoluciones | |
---|---|
The list of displays. Default always returns the default display 0. |
Lanza | |
---|---|
DeviceNotAvailableException |
listDisplayIdsForStartingVisibleBackgroundUsers
publiclistDisplayIdsForStartingVisibleBackgroundUsers ()
Gets the list of displays that can be used to start a user visible in the background
.
Devoluciones | |
---|---|
Lanza | |
---|---|
DeviceNotAvailableException |
listUsers
publiclistUsers ()
Gets the list of users on the device. Will throw DeviceRuntimeException
if output from device is not as expected.
Devoluciones | |
---|---|
the list of user ids. |
Lanza | |
---|---|
DeviceNotAvailableException |
logAnrs
public boolean logAnrs (ITestLogger logger)
Collects and log ANRs from the device.
Parámetros | |
---|---|
logger | ITestLogger : an ITestLogger to log the ANRs. |
Devoluciones | |
---|---|
boolean | True if the logging was successful, false otherwise. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
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.
Lanza | |
---|---|
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.
Lanza | |
---|---|
| 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.
Lanza | |
---|---|
| 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)Lanza | |
---|---|
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 |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if file was pulled successfully. false otherwise. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | true if file was retrieved successfully. false otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
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) |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
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) |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if file was retrieved successfully. false otherwise. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | A ERROR(/String) containing the contents of the device file, or null if the copy failed for any reason (including problems with the host filesystem) |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
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) |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if file was pushed successfully. false otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if file was pushed successfully. false otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if file was pushed successfully. false otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if file was pushed successfully. false otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if string was pushed successfully. false otherwise. |
Lanza | |
---|---|
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. |
Lanza | |
---|---|
DeviceNotAvailableException |
reboot
public void reboot ()
Reboots the device into adb mode.
Blocks until device becomes available.Lanza | |
---|---|
DeviceNotAvailableException |
rebootIntoBootloader
public void rebootIntoBootloader ()
Reboots the device into bootloader mode.
Blocks until device is in bootloader mode.Lanza | |
---|---|
DeviceNotAvailableException |
rebootIntoFastbootd
public void rebootIntoFastbootd ()
Reboots the device into fastbootd mode.
Blocks until device is in fastbootd mode.
Lanza | |
---|---|
DeviceNotAvailableException |
rebootIntoRecovery
public void rebootIntoRecovery ()
Reboots the device into adb recovery mode.
Blocks until device enters recoveryLanza | |
---|---|
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
Lanza | |
---|---|
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 |
Lanza | |
---|---|
DeviceNotAvailableException |
rebootUntilOnline
public void rebootUntilOnline ()
An alternate to reboot()
that only blocks until device is online ie visible to adb.
Lanza | |
---|---|
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. |
Lanza | |
---|---|
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.
Lanza | |
---|---|
DeviceNotAvailableException |
rebootUserspaceUntilOnline
public void rebootUserspaceUntilOnline ()
An alternate to rebootUserspace()
()} that only blocks until device is online ie visible to adb.
Lanza | |
---|---|
DeviceNotAvailableException |
recoverDevice
public boolean recoverDevice ()
Attempts to recover device communication.
Devoluciones | |
---|---|
boolean | True if recovery attempted and successful, returns False if recovery was skipped |
Lanza | |
---|---|
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. |
remountSystemWritable
public void remountSystemWritable ()
Make the system partition on the device writable. May reboot the device.
Lanza | |
---|---|
DeviceNotAvailableException |
remountVendorWritable
public void remountVendorWritable ()
Make the vendor partition on the device writable. May reboot the device.
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | True if it is successful, false otherwise. |
Lanza | |
---|---|
DeviceNotAvailableException |
removeOwners
public void removeOwners ()
Remove all existing device profile owners with the best effort.
Lanza | |
---|---|
DeviceNotAvailableException |
removeUser
public boolean removeUser (int userId)
Remove a given user from the device.
Parámetros | |
---|---|
userId | int : of the user to remove |
Devoluciones | |
---|---|
boolean | true if we were successful in removing the user, false otherwise. |
Lanza | |
---|---|
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) |
Devoluciones | |
---|---|
boolean | true if test command completed. false if it failed to complete, but recovery succeeded |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if test command completed. false if it failed to complete due to device communication exception, but recovery succeeded |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
DeviceNotAvailableException |
setConfiguration
public void setConfiguration (IConfiguration configuration)
Injects the IConfiguration
in use.
Parámetros | |
---|---|
configuration | IConfiguration |
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 |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | True if it is successful, false otherwise. |
Lanza | |
---|---|
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 ERROR(/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 IDevicePará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. |
Devoluciones | |
---|---|
boolean | returns True if the setprop command was successful, False otherwise. |
Lanza | |
---|---|
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, etcPará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 |
Lanza | |
---|---|
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 |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if the user was successfully started in the background. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | true if the user was successfully started in the background. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | true if the user was successfully started visible in the background. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | true if the user was successfully stopped. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | true if the user was successfully stopped. |
Lanza | |
---|---|
DeviceNotAvailableException |
switchToAdbTcp
public String switchToAdbTcp ()
Switch device to adb-over-tcp mode.
Devoluciones | |
---|---|
String | the tcp serial number or null if device could not be switched |
Lanza | |
---|---|
DeviceNotAvailableException |
switchToAdbUsb
public boolean switchToAdbUsb ()
Switch device to adb over usb mode.
Devoluciones | |
---|---|
boolean | true if switch was successful, false otherwise. |
Lanza | |
---|---|
DeviceNotAvailableException |
switchUser
public boolean switchUser (int userId)
Switch to another userId with a default timeout. switchUser(int, long)
.
Parámetros | |
---|---|
userId | int |
Devoluciones | |
---|---|
boolean | True if the new userId matches the userId provider. False otherwise. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | True if the new userId matches the userId provider. False otherwise. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if files were synced successfully. false otherwise. |
Lanza | |
---|---|
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()
.
Devoluciones | |
---|---|
Bugreport |
uninstallPackage
public String uninstallPackage (String packageName)
Uninstall an Android package from device.
Parámetros | |
---|---|
packageName | String : the Android package to uninstall |
Devoluciones | |
---|---|
String | a ERROR(/String) with an error code, or null if success. |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | a ERROR(/String) with an error code, or null if success. |
Lanza | |
---|---|
DeviceNotAvailableException |
unlockDevice
public boolean unlockDevice ()
Unlocks the device if the device is in an encrypted state.
This method may restart the framework but will not callpostBootSetup()
. Therefore, the device might not be fully ready to be tested when this method returns.Devoluciones | |
---|---|
boolean | true if successful or if the device is unencrypted. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if device's boot complete flag is set within the timeout |
Lanza | |
---|---|
DeviceNotAvailableException |
waitForDeviceAvailable
public boolean waitForDeviceAvailable ()
Waits for the device to be responsive and available for testing. Uses default timeout.
Devoluciones | |
---|---|
boolean | True if device is available, False if recovery is disabled and unavailable. |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | True if device is available, False if recovery is disabled and unavailable. |
Lanza | |
---|---|
DeviceNotAvailableException |
waitForDeviceAvailableInRecoverPath
public boolean waitForDeviceAvailableInRecoverPath (long waitTime)
Waits for the device to be responsive and available without considering recovery path.
Parámetros | |
---|---|
waitTime | long |
Devoluciones | |
---|---|
boolean | True if device is available, False if unavailable. |
Lanza | |
---|---|
DeviceNotAvailableException |
waitForDeviceBootloader
public void waitForDeviceBootloader ()
Blocks until device is visible via fastboot. Use default timeout.
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if device becomes not available before time expires. false otherwise |
waitForDeviceOnline
public void waitForDeviceOnline ()
Blocks until device is visible via adb. Uses default timeout
Note the device may not necessarily be responsive to commands on completion. UsewaitForDeviceAvailable()
instead.Lanza | |
---|---|
DeviceNotAvailableException |
waitForDeviceOnline
public void waitForDeviceOnline (long waitTime)
Blocks until device is visible via adb.
Note the device may not necessarily be responsive to commands on completion. UsewaitForDeviceAvailable()
instead.Parámetros | |
---|---|
waitTime | long : the time in ms to wait |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
boolean | true if device becomes responsive before waitTime elapses. |
Métodos protegidos
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 |
Devoluciones | |
---|---|
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. |
Devoluciones | |
---|---|
NativeDevice.RebootDeviceAction | the created RebootDeviceAction . |
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. |
Lanza | |
---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException |
ensureRuntimePermissionSupported
protected void ensureRuntimePermissionSupported ()
helper method to throw exception if runtime permission isn't supported
Lanza | |
---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException |
getApiLevelSafe
protected int getApiLevelSafe ()
Devoluciones | |
---|---|
int |
initializeConnection
protected void initializeConnection (IBuildInfo info, MultiMap<String, String> attributes)
Parámetros | |
---|---|
info | IBuildInfo |
attributes | MultiMap |
Lanza | |
---|---|
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. |
Devoluciones | |
---|---|
String | A string, possibly null or empty, containing the value of the given property |
Lanza | |
---|---|
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.
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
boolean |
notifyRebootEnded
protected void notifyRebootEnded ()
Notifies all IDeviceActionReceiver
about reboot end event.
Lanza | |
---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException |
notifyRebootStarted
protected void notifyRebootStarted ()
Notifies all IDeviceActionReceiver
about reboot start event.
Lanza | |
---|---|
| 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 |
Devoluciones | |
---|---|
boolean | true if action was performed successfully |
Lanza | |
---|---|
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.
Lanza | |
---|---|
| 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.
Lanza | |
---|---|
| com.android.tradefed.device.DeviceNotAvailableException |
DeviceNotAvailableException |
pullFileInternal
protected boolean pullFileInternal (String remoteFilePath, File localFile)
Parámetros | |
---|---|
remoteFilePath | String |
localFile | File |
Devoluciones | |
---|---|
boolean |
Lanza | |
---|---|
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 |
Devoluciones | |
---|---|
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 |
Devoluciones | |
---|---|
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. |
Devoluciones | |
---|---|
boolean | True if device did become unavailable. |
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2023-04-28 (UTC)