NativeDevice

public class NativeDevice
extends Object implements IManagedTestDevice , IConfigurationReceiver , ITestLoggerReceiver

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


Implémentation par défaut d'un ITestDevice Appareils Android non full stack.

Résumé

Classes imbriquées

class NativeDevice.AdbAction

Une ERROR(DeviceAction/com.android.tradefed.device.NativeDevice.DeviceAction DeviceAction) pour l'exécution d'une commande OS 'adb ....'.

class NativeDevice.AdbShellAction

class NativeDevice.RebootDeviceAction

ERROR(DeviceAction/com.android.tradefed.device.NativeDevice.DeviceAction DeviceAction) pour redémarrer un appareil.

Constantes

int INVALID_USER_ID

Valeur renvoyée pour tout ID utilisateur invalide/introuvable : UserHandle a défini la valeur -10000

long MAX_HOST_DEVICE_TIME_OFFSET

int MAX_RETRY_ATTEMPTS

le nombre par défaut de nouvelles tentatives de commande à effectuer

Des champs

protected static final String SD_CARD

protected static final String STORAGE_EMULATED

protected TestDeviceOptions mOptions

protected final IDeviceStateMonitor mStateMonitor

Constructeurs publics

NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)

Crée un TestDevice .

Méthodes publiques

boolean canSwitchToHeadlessSystemUser ()

Renvoie s'il est autorisé à passer à l'utilisateur SYSTEM sans tête.

boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

Vérifiez si une fonctionnalité est actuellement prise en charge en fonction d'un niveau de prise en charge minimal.

boolean checkConnectivity ()

Vérifiez que l'appareil dispose d'une connectivité réseau.

boolean clearErrorDialogs ()

Essayez de fermer toutes les boîtes de dialogue d'erreur actuellement affichées sur l'interface utilisateur de l'appareil.

void clearLastConnectedWifiNetwork ()

Efface le dernier réseau Wi-Fi connecté.

void clearLogcat ()

Supprime toutes les données logcat accumulées.

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

Se connecte à un réseau wifi.

boolean connectToWifiNetwork (String wifiSsid, String wifiPsk)

Se connecte à un réseau wifi.

boolean connectToWifiNetwork ( wifiSsidToPsk) connectToWifiNetwork ( wifiSsidToPsk)

Se connecte à un réseau wifi.f

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

Se connecte à un réseau wifi.

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

Une variante de connectToWifiNetwork(String, String) qui se connecte uniquement si l'appareil n'a actuellement pas de connectivité réseau.

boolean connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk)

Une variante de connectToWifiNetwork(String, String) qui se connecte uniquement si l'appareil n'a actuellement pas de connectivité réseau.

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

Créer un utilisateur avec un nom donné et les drapeaux fournis

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

Créer un utilisateur avec un nom donné et les drapeaux fournis

int createUser (String name)

Créez un utilisateur avec un nom donné et des drapeaux par défaut 0.

int createUserNoThrow (String name)

Créez un utilisateur avec un nom donné et des drapeaux par défaut 0.

void deleteFile (String deviceFilePath)

Méthode d'assistance pour supprimer un fichier ou un répertoire sur l'appareil.

void deregisterDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver)

Supprime le IDeviceActionReceiver enregistré.

boolean deviceSoftRestarted ( ProcessInfo prevSystemServerProcess)

Méthode d'assistance pour vérifier si l'appareil a redémarré en douceur en comparant le system_server actuel avec le system_server précédent ProcessInfo .

boolean deviceSoftRestartedSince (long utcEpochTime, TimeUnit timeUnit)

Méthode d'assistance pour vérifier si l'appareil a redémarré en douceur depuis l'heure UTC depuis l'époque de l'appareil et son ERROR(/TimeUnit) .

boolean disableAdbRoot ()

Désactive la racine adb.

void disableKeyguard ()

Tente de désactiver le verrouillage du clavier.

boolean disableNetworkMonitor ()

Désactive la surveillance du réseau sur l'appareil.

boolean disconnectFromWifi ()

Se déconnecte d'un réseau wifi.

boolean doesFileExist (String deviceFilePath, int userId)

Méthode d'assistance pour déterminer si le fichier sur l'appareil existe pour un utilisateur donné.

boolean doesFileExist (String deviceFilePath)

Méthode d'assistance pour déterminer si le fichier sur l'appareil existe.

File dumpHeap (String process, String devicePath)

Essayez de vider le tas du system_server.

boolean enableAdbRoot ()

Active la racine adb.

boolean enableNetworkMonitor ()

Active la surveillance du réseau sur l'appareil.

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

Méthode d'assistance qui exécute une commande adb en tant que commande système avec un délai d'attente spécifié.

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

Méthode d'assistance qui exécute une commande adb en tant que commande système avec un délai d'attente spécifié.

String executeAdbCommand (String... cmdArgs)

Méthode d'assistance qui exécute une commande adb en tant que commande système.

CommandResult executeFastbootCommand (String... cmdArgs)

Méthode d'assistance qui exécute une commande fastboot en tant que commande système avec un délai d'attente par défaut de 2 minutes.

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

Méthode d'assistance qui exécute une commande fastboot en tant que commande système.

CommandResult executeLongFastbootCommand (String... cmdArgs)

Méthode d'assistance qui exécute une longue commande fastboot en tant que commande système.

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

Méthode d'assistance qui exécute une longue commande fastboot en tant que commande système avec des variables d'environnement système.

String executeShellCommand (String command)

Méthode d'assistance qui exécute une commande shell adb et renvoie la sortie sous la forme d'une ERROR(/String) .

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

void executeShellCommand (String command, IShellOutputReceiver receiver)

Exécute la commande shell adb donnée, en réessayant plusieurs fois si la commande échoue.

CommandResult executeShellV2Command (String cmd)

Méthode d'assistance qui exécute une commande shell adb et renvoie les résultats sous la forme d'un CommandResult correctement rempli avec la sortie de l'état de la commande, stdout et stderr.

CommandResult executeShellV2Command (String cmd, OutputStream pipeToOutput)

Méthode d'assistance qui exécute une commande shell adb et renvoie les résultats sous la forme d'un CommandResult correctement rempli avec la sortie de l'état de la commande et stderr.

CommandResult executeShellV2Command (String cmd, File pipeAsInput)

Méthode d'assistance qui exécute une commande shell adb et renvoie les résultats sous la forme d'un CommandResult correctement rempli avec la sortie d'état de la commande, stdout et stderr.

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

CommandResult fastbootWipePartition (String partition)

Méthode d'assistance qui efface une partition pour le périphérique.

getActiveApexes ()

Récupérez les informations sur les APEX activés sur l'appareil.

getAllSettings (String namespace)

Renvoie les paires clé-valeur de l'espace de noms demandé.

DeviceAllocationState getAllocationState ()

Renvoie l'état d'allocation actuel de l'appareil

String getAndroidId (int userId)

Recherche et renvoie l'identifiant android associé à un userId, null s'il n'est pas trouvé.

getAndroidIds ()

Créez une carte des identifiants Android trouvés correspondant aux identifiants d'utilisateur.

int getApiLevel ()

Obtenez le niveau d'API de l'appareil.

PackageInfo getAppPackageInfo (String packageName)

Récupérer des informations sur un package installé sur l'appareil.

getAppPackageInfos ()

Récupérer les informations des packages installés sur l'appareil.

String getBasebandVersion ()

Méthode pratique pour obtenir la version bande de base (radio) de cet appareil.

Integer getBattery ()

Renvoie le niveau de batterie actuel d'un appareil ou Null si le niveau de batterie n'est pas disponible.

boolean getBooleanProperty (String name, boolean defaultValue)

Renvoie la valeur booléenne de la propriété donnée.

getBootHistory ()

La méthode d'assistance collecte la carte de l'historique de démarrage avec l'heure de démarrage et la raison du démarrage.

getBootHistorySince (long utcEpochTime, TimeUnit timeUnit)

La méthode d'assistance collecte la carte de l'historique de démarrage avec l'heure de démarrage et la raison du démarrage depuis le temps donné depuis l'époque du périphérique et l'unité de temps spécifiée.

String getBootloaderVersion ()

Méthode pratique pour obtenir la version bootloader de cet appareil.

InputStreamSource getBugreport ()

Récupère un rapport de bogue de l'appareil.

InputStreamSource getBugreportz ()

Récupère un bugreportz de l'appareil.

String getBuildAlias ()

Récupérez l'alias de la version que l'appareil exécute actuellement.

String getBuildFlavor ()

Récupérez la saveur de construction pour le périphérique.

String getBuildId ()

Récupérez la version que l'appareil exécute actuellement.

String getBuildSigningKeys ()

Renvoie le type de clé utilisé pour signer l'image de l'appareil

Généralement, les appareils Android peuvent être signés avec des clés de test (comme dans AOSP) ou des clés de libération (contrôlées par les fabricants d'appareils individuels)

DeviceDescriptor getCachedDeviceDescriptor ()

Renvoie un DeviceDescriptor mis en cache si le périphérique est alloué, sinon renvoie le DeviceDescriptor actuel.

DeviceDescriptor getCachedDeviceDescriptor (boolean shortDescriptor)

Renvoie un DeviceDescriptor mis en cache si le périphérique est alloué, sinon renvoie le DeviceDescriptor actuel.

String[] getChildren (String path)

Alternative à l'utilisation IFileEntry qui ne fonctionne parfois pas à cause des autorisations.

AbstractConnection getConnection ()

La connexion actuelle associée à l'appareil.

DeviceFoldableState getCurrentFoldableState ()

Renvoie l'état pliable actuel de l'appareil ou null si des problèmes se sont produits.

int getCurrentUser ()

Renvoie l'identifiant de l'utilisateur en cours d'exécution.

String getDeviceClass ()

Obtenez la classe d'appareil.

long getDeviceDate ()

Renvoie la date de l'appareil en millisecondes depuis l'époque.

DeviceDescriptor getDeviceDescriptor ()

Renvoyez un DeviceDescriptor à partir des informations sur le périphérique pour obtenir des informations dessus sans passer l'objet périphérique réel.

DeviceDescriptor getDeviceDescriptor (boolean shortDescriptor)

Renvoyez un DeviceDescriptor à partir des informations sur le périphérique pour obtenir des informations dessus sans passer l'objet périphérique réel.

TestDeviceState getDeviceState ()

Obtenez l'état de l'appareil.

long getDeviceTimeOffset (Date date)

Aide pour obtenir la différence de temps entre l'appareil et une ERROR(/Date) donnée.

InputStreamSource getEmulatorOutput ()

Obtenez le flux de l'émulateur stdout et stderr

Process getEmulatorProcess ()

Renvoie l' ERROR(/Process) correspondant à cet émulateur.

final File getExecuteShellCommandLog ()

Le journal qui contient tous les journaux executeShellCommand(String) .

long getExternalStoreFreeSpace ()

Méthode d'assistance pour déterminer la quantité d'espace libre sur le stockage externe de l'appareil.

String getFastbootPath ()

Renvoie le chemin du binaire fastboot utilisé.

String getFastbootProductType ()

Méthode pratique pour obtenir le type de produit de cet appareil lorsqu'il est en mode de démarrage rapide.

String getFastbootProductVariant ()

Méthode pratique pour obtenir le type de produit de cet appareil lorsqu'il est en mode de démarrage rapide.

String getFastbootSerialNumber ()

Renvoie le numéro de série du mode de démarrage rapide.

String getFastbootVariable (String variableName)

Récupérez la valeur de la variable fastboot donnée à partir du périphérique.

String getFastbootVersion ()

Renvoie la chaîne de version du binaire fastboot utilisé.

IFileEntry getFileEntry (String path)

Récupérer une référence à un fichier distant sur l'appareil.

IFileEntry getFileEntry (FileListingService.FileEntry entry)

Assistant non officiel pour obtenir un FileEntry à partir d'un chemin non racine.

getFoldableStates ()

Renvoie la liste des états pliables sur l'appareil.

IDevice getIDevice ()

Renvoie une référence à l' IDevice ddmlib associé .

getInstalledPackageNames ()

Récupérez les noms des packages d'applications présents sur l'appareil.

long getIntProperty (String name, long defaultValue)

Renvoie la valeur entière de la propriété donnée à partir du périphérique.

String getIpAddress ()

Obtient l'adresse IP de l'appareil.

KeyguardControllerState getKeyguardState ()

Renvoie un objet pour obtenir l'état actuel du keyguard ou null s'il n'est pas pris en charge.

long getLastExpectedRebootTimeMillis ()

Renvoie la dernière fois que les API Tradefed ont déclenché un redémarrage en millisecondes depuis EPOCH tel que renvoyé par ERROR(/System#currentTimeMillis()) .

int getLaunchApiLevel ()

Obtenez le premier niveau d'API lancé de l'appareil.

InputStreamSource getLogcat ()

Saisit un flux d'instantané des données logcat.

InputStreamSource getLogcat (int maxBytes)

Saisit un flux d'instantané des derniers maxBytes de données logcat capturées.

InputStreamSource getLogcatDump ()

Obtenez un vidage du logcat actuel pour le périphérique.

InputStreamSource getLogcatSince (long date)

Saisit un flux d'instantané des données logcat capturées à partir de la date fournie.

String getMacAddress ()

Renvoie l'adresse MAC de l'appareil, null s'il ne parvient pas à interroger l'appareil.

Integer getMainUserId ()

Renvoie l'identifiant de l'utilisateur principal.

getMainlineModuleInfo ()

Obtenez les informations sur les modules principaux installés sur l'appareil.

int getMaxNumberOfRunningUsersSupported ()

Obtenez le nombre maximum d'utilisateurs fonctionnant simultanément pris en charge.

int getMaxNumberOfUsersSupported ()

Obtenez le nombre maximum d'utilisateurs pris en charge.

Process getMicrodroidProcess ()
IDeviceStateMonitor getMonitor ()

Renvoie le IDeviceStateMonitor associé au périphérique.

String getMountPoint (String mountName)

Renvoie un point de montage.

ITestDevice.MountPointInfo getMountPointInfo (String mountpoint)

Renvoie un MountPointInfo correspondant au chemin du point de montage spécifié, ou null si ce chemin n'a rien de monté ou n'apparaît pas dans /proc/mounts en tant que point de montage.

getMountPointInfo ()

Renvoie une version analysée des informations dans /proc/mounts sur le périphérique

TestDeviceOptions getOptions ()

Récupérez les options de test pour l'appareil.

long getPartitionFreeSpace (String partition)

Méthode d'assistance pour déterminer la quantité d'espace libre sur la partition de l'appareil.

Integer getPrimaryUserId ()

Renvoie l'ID utilisateur principal.

ProcessInfo getProcessByName (String processName)

La méthode d'assistance exécute les commandes "pidof" et "stat" et renvoie l'objet ProcessInfo avec le PID et l'heure de début du processus donné.

String getProcessPid (String process)

Renvoie le pid du service ou null si quelque chose s'est mal passé.

String getProductType ()

Méthode pratique pour obtenir le type de produit de cet appareil.

String getProductVariant ()

Méthode pratique pour obtenir la variante de produit de cet appareil.

String getProperty (String name)

Récupérez la valeur de propriété donnée à partir de l'appareil.

ITestDevice.RecoveryMode getRecoveryMode ()

Obtenez le mode de récupération actuel utilisé pour l'appareil.

InputStreamSource getScreenshot (String format)

Prend une capture d'écran de l'appareil.

InputStreamSource getScreenshot (long displayId)

Prend une capture d'écran de l'appareil avec l'identifiant d'affichage.

InputStreamSource getScreenshot (String format, boolean rescale)

Prend une capture d'écran de l'appareil.

InputStreamSource getScreenshot ()

Prend une capture d'écran de l'appareil.

String getSerialNumber ()

Méthode pratique pour obtenir le numéro de série de cet appareil.

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

Renvoie la valeur du paramètre demandé.

String getSetting (String namespace, String key)

Voir getSetting(int, String, String) et effectué sur l'utilisateur système.

String getSimOperator ()

Renvoie l'opérateur de la carte SIM ou null si non disponible ou si l'appareil n'est pas disponible.

String getSimState ()

Renvoie l'état de la carte SIM ou null si non disponible ou si l'appareil n'est pas disponible.

getTombstones ()

Récupérez et renvoyez la liste des pierres tombales des appareils.

long getTotalMemory ()

Renvoie la taille totale de la mémoire physique en octets ou -1 en cas d'erreur interne

getUninstallablePackageNames ()

Récupérez les noms des packages d'application qui peuvent être désinstallés.

boolean getUseFastbootErase ()

Déterminez si vous souhaitez utiliser l'effacement de démarrage rapide ou le format de démarrage rapide pour effacer une partition sur l'appareil.

int getUserFlags (int userId)

Recherche et renvoie les drapeaux d'un utilisateur donné.

getUserInfos ()

Obtient la carte de useId à UserInfo sur l'appareil.

int getUserSerialNumber (int userId)

Renvoie le numéro de série associé à l'userId s'il est trouvé, -10000 dans tous les autres cas.

IManagedTestDevice.DeviceEventResponse handleAllocationEvent (DeviceEvent event)

Traitez le DeviceEvent donné.

Traiter le DeviceEvent, qui peut ou non faire passer ce périphérique à un nouvel état d'allocation.

boolean hasFeature (String feature)

Vérifiez si une fonctionnalité est disponible sur un appareil.

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

Installez un package Android sur l'appareil.

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

Installez un package Android sur l'appareil.

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

Installez un package Android sur l'appareil pour un utilisateur donné.

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

Installez un package Android sur l'appareil pour un utilisateur donné.

void invalidatePropertyCache ()
boolean isAdbRoot ()

boolean isAdbTcp ()
boolean isAppEnumerationSupported ()

Vérifiez si la plate-forme sur l'appareil prend en charge l'énumération des applications

boolean isBypassLowTargetSdkBlockSupported ()

Vérifiez si la plate-forme sur l'appareil prend en charge le contournement du bloc SDK cible faible lors des installations d'applications

boolean isDeviceEncrypted ()

Renvoie si l'appareil est chiffré.

boolean isDirectory (String path)

Renvoie True si le chemin sur le périphérique est un répertoire, false sinon.

boolean isEnableAdbRoot ()
boolean isEncryptionSupported ()

Renvoie si le chiffrement est pris en charge sur l'appareil.

boolean isExecutable (String fullPath)

Renvoie True si le chemin du fichier sur le périphérique est un fichier exécutable, false sinon.

boolean isFastbootEnabled ()

Renvoie si fastboot est disponible pour le périphérique.

boolean isHeadless ()

Renvoie vrai si l'appareil est sans écran (pas d'écran), faux sinon.

boolean isHeadlessSystemUserMode ()

Indique si l'appareil utilise le mode utilisateur du système sans tête.

boolean isMainUserPermanentAdmin ()

Indique si l'utilisateur principal est un administrateur permanent et ne peut pas être supprimé ou rétrogradé au statut de non-administrateur.

boolean isMultiUserSupported ()

Détermine si le multi-utilisateur est pris en charge.

boolean isPackageInstalled (String packageName, String userId)

Interrogez l'appareil pour un nom de package donné et un identifiant d'utilisateur donné pour vérifier s'il est actuellement installé ou non pour cet utilisateur.

boolean isPackageInstalled (String packageName)

Interrogez l'appareil pour un nom de package donné pour vérifier s'il est actuellement installé ou non.

boolean isRuntimePermissionSupported ()

Vérifiez si la plate-forme sur l'appareil prend en charge l'octroi d'autorisations d'exécution

boolean isStateBootloaderOrFastbootd ()

Renvoie true si le périphérique est dans TestDeviceState#FASTBOOT ou TestDeviceState.FASTBOOTD .

boolean isUserRunning (int userId)

Vérifiez si un utilisateur donné est en cours d'exécution.

boolean isUserSecondary (int userId)

Retourne si l'utilisateur spécifié est un utilisateur secondaire selon ses drapeaux.

boolean isUserVisible (int userId)

Vérifie si l'utilisateur donné est visible.

boolean isUserVisibleOnDisplay (int userId, int displayId)

Vérifie si l'utilisateur donné est visible dans l'affichage donné.

boolean isVisibleBackgroundUsersOnDefaultDisplaySupported ()

Indique si l'appareil autorise les utilisateurs à démarrer visible en arrière-plan dans le ERROR(/java.android.view.Display#DEFAULT_DISPLAY) .

boolean isVisibleBackgroundUsersSupported ()

Indique si l'appareil permet aux utilisateurs d'être visibles en arrière-plan.

boolean isWifiEnabled ()

Testez si le wifi est activé.

listDisplayIds ()

Collectez la liste des identifiants d'affichage disponibles sur l'appareil, comme indiqué par "dumpsys SurfaceFlinger".

listDisplayIdsForStartingVisibleBackgroundUsers ()

Obtient la liste des affichages pouvant être utilisés pour start a user visible in the background .

listUsers ()

Obtient la liste des utilisateurs sur l'appareil.

boolean logAnrs ( ITestLogger logger)

Collecte et enregistre les ANR de l'appareil.

boolean logBugreport (String dataName, ITestLogger listener)

Méthode d'assistance pour prendre un rapport de bogue et le consigner aux reporters.

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

Enregistrez un message dans le logcat de l'appareil.

void nonBlockingReboot ()

Émet une commande pour redémarrer l'appareil et revient une fois la commande terminée et lorsque l'appareil n'est plus visible pour adb.

void postAdbRootAction ()

Remplacez si l'appareil a besoin d'actions spécifiques à prendre après la racine adb et avant que l'appareil ne soit de nouveau en ligne.

void postAdbUnrootAction ()

Remplacez si l'appareil a besoin d'actions spécifiques à entreprendre après la suppression de la racine d'adb et avant que l'appareil ne soit de nouveau en ligne.

void postBootSetup ()

Exécutez les instructions pour configurer le périphérique afin de le tester après chaque démarrage.

void postInvocationTearDown (Throwable exception)

Étapes supplémentaires pour le nettoyage requis spécifique à l'appareil qui seront exécutés une fois l'invocation terminée.

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

Étapes supplémentaires pour la configuration requise spécifique à l'appareil qui seront exécutées sur l'appareil avant le flux d'appel.

boolean pullDir (String deviceFilePath, File localDir)

Extraction récursive du contenu du répertoire à partir de l'appareil.

boolean pullFile (String remoteFilePath, File localFile)

Récupère un fichier hors de l'appareil.

File pullFile (String remoteFilePath, int userId)

Récupère un fichier hors de l'appareil, le stocke dans un ERROR(/File) local temporaire et renvoie ce File .

File pullFile (String remoteFilePath)

Récupère un fichier hors de l'appareil, le stocke dans un ERROR(/File) local temporaire et renvoie ce File .

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

Récupère un fichier hors de l'appareil.

String pullFileContents (String remoteFilePath)

Récupère un fichier hors de l'appareil et renvoie le contenu.

File pullFileFromExternal (String remoteFilePath)

Une méthode pratique pour récupérer un fichier à partir du stockage externe de l'appareil, le stocker dans un ERROR(/File) local temporaire et renvoyer une référence à ce File .

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

Poussez récursivement le contenu des répertoires vers l'appareil tout en excluant certains répertoires filtrés.

boolean pushDir (File localFileDir, String deviceFilePath)

Poussez récursivement le contenu du répertoire vers le périphérique.

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

Variante de pushFile(File, String) qui peut éventuellement envisager d'évaluer le besoin du fournisseur de contenu.

boolean pushFile (File localFile, String remoteFilePath)

Pousser un fichier vers l'appareil.

boolean pushString (String contents, String remoteFilePath)

Pousser le fichier créé à partir d'une chaîne vers l'appareil

void reboot (String reason)

Redémarre l'appareil en mode adb avec une reason donnée de persister lors du redémarrage.

void reboot ()

Redémarre l'appareil en mode adb.

void rebootIntoBootloader ()

Redémarre l'appareil en mode chargeur de démarrage.

void rebootIntoFastbootd ()

Redémarre l'appareil en mode fastbootd.

void rebootIntoRecovery ()

Redémarre l'appareil en mode de récupération adb.

void rebootIntoSideload ()

Redémarre l'appareil en mode adb sideload (notez qu'il s'agit d'un mode spécial en cours de récupération)

Bloque jusqu'à ce que l'appareil passe en mode chargement latéral

void rebootIntoSideload (boolean autoReboot)

Redémarre l'appareil en mode adb sideload (notez qu'il s'agit d'un mode spécial en cours de récupération)

Bloque jusqu'à ce que l'appareil passe en mode chargement latéral

void rebootUntilOnline ()

Une alternative à reboot() qui ne bloque que jusqu'à ce que l'appareil soit en ligne, c'est-à-dire visible par adb.

void rebootUntilOnline (String reason)

Une alternative à reboot() qui ne bloque que jusqu'à ce que l'appareil soit en ligne, c'est-à-dire visible par adb.

void rebootUserspace ()

Redémarre uniquement la partie de l'espace utilisateur de l'appareil.

void rebootUserspaceUntilOnline ()

Une alternative à rebootUserspace() ()} qui ne bloque que jusqu'à ce que l'appareil soit en ligne, c'est-à-dire visible par adb.

boolean recoverDevice ()

Tente de rétablir la communication de l'appareil.

void registerDeviceActionReceiver ( IDeviceActionReceiver deviceActionReceiver)

Enregistre un IDeviceActionReceiver pour ce périphérique.

void remountSystemWritable ()

Rendez la partition système sur le périphérique accessible en écriture.

void remountVendorWritable ()

Rendez la partition fournisseur sur le périphérique accessible en écriture.

boolean removeAdmin (String componentName, int userId)

Supprimez l'administrateur de l'appareil donné dans l'utilisateur donné et renvoyez true si cela réussit, false sinon.

void removeOwners ()

Supprimez tous les propriétaires de profils d'appareils existants avec le meilleur effort.

boolean removeUser (int userId)

Supprimer un utilisateur donné de l'appareil.

void resetContentProviderSetup ()

Réinitialisez l'indicateur de configuration du fournisseur de contenu afin de le déclencher à nouveau.

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

Méthode pratique pour effectuer ERROR(/#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection)) avec un ou plusieurs écouteurs passés en paramètres.

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

Exécute des tests d'instrumentation et fournit une récupération de périphérique.

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

Identique à ERROR(ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)/com.android.tradefed.device.ITestDevice#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection) ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)) mais exécute le test pour l'utilisateur donné.

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

Identique à ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, ITestLifeCycleReceiver...) mais exécute le test pour un utilisateur donné.

void setConfiguration ( IConfiguration configuration)

Injecte la IConfiguration en cours d'utilisation.

void setDate (Date date)

Définit la date sur l'appareil

Remarque : le réglage de la date sur l'appareil nécessite root

boolean setDeviceOwner (String componentName, int userId)

Définissez un composant d'administration de l'appareil en tant que propriétaire de l'appareil dans un utilisateur donné.

void setDeviceState ( TestDeviceState deviceState)

Mettez à jour l'état de l'appareil.

void setEmulatorOutputStream ( SizeLimitedOutputStream output)

Pour l'émulateur, définissez SizeLimitedOutputStream pour enregistrer la sortie

void setEmulatorProcess (Process p)

Définit ERROR(/Process) , lorsque ce périphérique est un émulateur.

void setFastbootEnabled (boolean fastbootEnabled)

Définissez l'option de démarrage rapide pour le périphérique.

void setFastbootPath (String fastbootPath)

Définit le chemin vers le binaire fastboot qui doit être utilisé.

void setIDevice (IDevice newDevice)

Mettez à jour l'IDevice associé à cet ITestDevice.

void setLogStartDelay (int delay)

Définit le temps d'attente en ms avant de démarrer la capture du logcat pour un appareil en ligne.

void setOptions ( TestDeviceOptions options)

Définir les TestDeviceOptions pour le périphérique

boolean setProperty (String propKey, String propValue)

Définit la valeur de propriété donnée sur le périphérique.

void setRecovery ( IDeviceRecovery recovery)

Définissez IDeviceRecovery à utiliser pour cet appareil.

void setRecoveryMode ( ITestDevice.RecoveryMode mode)

Définissez le mode de récupération actuel à utiliser pour l'appareil.

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

Voir setSetting(int, String, String, String) et effectué sur l'utilisateur système.

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

Ajoutez une valeur de paramètre à l'espace de noms d'un utilisateur donné.

void setTestLogger ( ITestLogger testLogger)

Injecte l'instance ITestLogger

void setUseFastbootErase (boolean useFastbootErase)

Définissez si vous souhaitez utiliser l'effacement de démarrage rapide ou le format de démarrage rapide pour effacer une partition sur l'appareil.

void startLogcat ()

Commencez à capturer la sortie logcat de l'appareil en arrière-plan.

boolean startUser (int userId)

Démarre un utilisateur donné en arrière-plan s'il est actuellement arrêté.

boolean startUser (int userId, boolean waitFlag)

Démarre un utilisateur donné en arrière-plan s'il est actuellement arrêté.

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

Démarre un utilisateur donné en arrière-plan, visible dans l'affichage donné (c'est-à-dire, permettant à l'utilisateur de lancer des activités dans cet affichage).

void stopEmulatorOutput ()

Fermez et supprimez la sortie de l'émulateur.

void stopLogcat ()

Arrêtez de capturer la sortie logcat de l'appareil et supprimez les données logcat actuellement enregistrées.

boolean stopUser (int userId)

Arrête un utilisateur donné.

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

Arrêter un utilisateur donné.

String switchToAdbTcp ()

Basculez l'appareil en mode adb-over-tcp.

boolean switchToAdbUsb ()

Basculez l'appareil en mode adb sur usb.

boolean switchUser (int userId)

Basculez vers un autre ID utilisateur avec un délai d'expiration par défaut.

boolean switchUser (int userId, long timeout)

Passez à un autre ID utilisateur avec le délai d'expiration fourni comme date limite.

boolean syncFiles (File localFileDir, String deviceFilePath)

Synchronise de manière incrémentielle le contenu d'un répertoire de fichiers local sur l'appareil.

Bugreport takeBugreport ()

Prend un rapport de bogue et le renvoie dans un objet Bugreport pour le gérer.

String uninstallPackage (String packageName)

Désinstallez un package Android de l'appareil.

String uninstallPackageForUser (String packageName, int userId)

Désinstallez un package Android de l'appareil pour un utilisateur donné.

boolean unlockDevice ()

Déverrouille l'appareil si l'appareil est dans un état chiffré.

boolean waitForBootComplete (long timeOut)

Bloque jusqu'à ce que l'indicateur de démarrage complet de l'appareil soit défini.

boolean waitForDeviceAvailable ()

Attend que l'appareil soit réactif et disponible pour les tests.

boolean waitForDeviceAvailable (long waitTime)

Attend que l'appareil soit réactif et disponible pour les tests.

boolean waitForDeviceAvailableInRecoverPath (long waitTime)

Attend que l'appareil soit réactif et disponible sans tenir compte du chemin de récupération.

void waitForDeviceBootloader ()

Bloque jusqu'à ce que l'appareil soit visible via fastboot.

boolean waitForDeviceInRecovery (long waitTime)

Blocs pour que le périphérique soit dans l'état 'adb recovery' (notez que ceci est distinct de IDeviceRecovery ).

boolean waitForDeviceInSideload (long waitTime)

Blocs pour que l'appareil soit dans l'état 'adb sideload'

boolean waitForDeviceNotAvailable (long waitTime)

Blocs pour que l'appareil ne soit pas disponible, c'est-à-dire manquant dans adb

void waitForDeviceOnline ()

Bloque jusqu'à ce que l'appareil soit visible via adb.

void waitForDeviceOnline (long waitTime)

Bloque jusqu'à ce que l'appareil soit visible via adb.

boolean waitForDeviceShell (long waitTime)

Attend que l'appareil réponde à une commande de base du shell adb.

Méthodes protégées

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

Construit la commande du système d'exploitation pour la session de commande du shell adb donnée et les arguments

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

Créez une RebootDeviceAction à utiliser lors de l'exécution d'une action de redémarrage.

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

Effectuez un redémarrage adb.

void ensureRuntimePermissionSupported ()

méthode d'assistance pour lever une exception si l'autorisation d'exécution n'est pas prise en charge

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

Obtenez l'instance RunUtil à utiliser.

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

Récupérez une propriété de périphérique, à partir du cache ddmlib par défaut, et revenez à `adb shell getprop` ou `fastboot getvar` selon que le périphérique est dans Fastboot ou non.

boolean isInRebootCallback ()

Renvoie si les rappels de redémarrage sont en cours d'exécution ou non.

boolean isNewer (File localFile, IFileEntry entry)

Renvoie true si le fichier local est plus récent que le fichier distant.

void notifyRebootEnded ()

Avertit tous les IDeviceActionReceiver de l'événement de fin de redémarrage.

void notifyRebootStarted ()

Avertit tous les IDeviceActionReceiver de l'événement de démarrage du redémarrage.

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

Effectue une action sur cet appareil.

void postAdbReboot ()

Actions supplémentaires possibles pouvant être effectuées après un redémarrage.

void prePostBootSetup ()

Permet à chaque type de périphérique (AndroidNativeDevice, TestDevice) de remplacer cette méthode pour une configuration post-démarrage spécifique.

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

Définissez l'instance d'horloge à utiliser.

void setMicrodroidProcess (Process process)

Marque le TestDevice comme microdroid et définit son CID.

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

Exécute une simple commande fastboot avec des variables d'environnement et signale l'état de la commande.

CommandResult simpleFastbootCommand (long timeout, String[] fullCmd)

Exécute une simple commande fastboot et signale l'état de la commande.

boolean waitForDeviceNotAvailable (String operationDesc, long time)

Attendez de voir l'appareil devenir indisponible (arrêtez de signaler à adb).

Constantes

IDENTIFIANT INVALIDE

public static final int INVALID_USER_ID

Valeur renvoyée pour tout ID utilisateur invalide/introuvable : UserHandle a défini la valeur -10000

Valeur constante : -10000 (0xffffd8f0)

MAX_HOST_DEVICE_TIME_OFFSET

protected static final long MAX_HOST_DEVICE_TIME_OFFSET

Valeur constante : 5000 (0x0000000000001388)

MAX_RETRY_ATTENTTS

protected static final int MAX_RETRY_ATTEMPTS

le nombre par défaut de nouvelles tentatives de commande à effectuer

Valeur constante : 2 (0x00000002)

Des champs

CARTE SD

protected static final String SD_CARD

STORAGE_EMULATED

protected static final String STORAGE_EMULATED

mOptions

protected TestDeviceOptions mOptions

mStateMonitor

protected final IDeviceStateMonitor mStateMonitor

Constructeurs publics

NativeDevice

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

Crée un TestDevice .

Paramètres
device IDevice : l' IDevice associé

stateMonitor IDeviceStateMonitor : le mécanisme IDeviceStateMonitor à utiliser

allocationMonitor IDeviceMonitor : l' IDeviceMonitor pour informer des changements d'état d'allocation. Peut être nul

Méthodes publiques

canSwitchToHeadlessSystemUser

public boolean canSwitchToHeadlessSystemUser ()

Renvoie s'il est autorisé à passer à l'utilisateur SYSTEM sans tête.

Retour
boolean

Lance
DeviceNotAvailableException

checkApiLevelAgainstNextRelease

public boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

Vérifiez si une fonctionnalité est actuellement prise en charge en fonction d'un niveau de prise en charge minimal. Cette méthode prend en compte les fonctionnalités non encore publiées, avant que le niveau de l'API ne soit augmenté.

Paramètres
strictMinLevel int : le niveau minimum strict possible qui prend en charge la fonctionnalité.

Retour
boolean Vrai si le niveau est pris en charge. Faux sinon.

Lance
DeviceNotAvailableException

checkConnectivité

public boolean checkConnectivity ()

Vérifiez que l'appareil dispose d'une connectivité réseau.

Retour
boolean true si l'appareil dispose d'une connexion réseau fonctionnelle, false dans le cas contraire.

Lance
DeviceNotAvailableException

clearErrorDialogs

public boolean clearErrorDialogs ()

Essayez de fermer toutes les boîtes de dialogue d'erreur actuellement affichées sur l'interface utilisateur de l'appareil.

Retour
boolean true si aucune boîte de dialogue n'était présente ou si les boîtes de dialogue ont été effacées avec succès. false sinon.

Lance
DeviceNotAvailableException

clearLastConnectedWifiNetwork

public void clearLastConnectedWifiNetwork ()

Efface le dernier réseau Wi-Fi connecté. Il doit être appelé lors du démarrage d'une nouvelle invocation pour éviter de se connecter au réseau wifi utilisé lors du test précédent après le redémarrage de l'appareil.

clearLogcat

public void clearLogcat ()

Supprime toutes les données logcat accumulées.

Ceci est utile dans les cas où vous voulez vous assurer que ITestDevice#getLogcat() ne renvoie que les données de journal produites après un certain point (comme après avoir flashé une nouvelle version de périphérique, etc.).

connectToWifiNetwork

public boolean connectToWifiNetwork ( wifiSsidToPsk, 
                boolean scanSsid)

Se connecte à un réseau wifi.

Active le wifi et bloque jusqu'à ce qu'une connexion réussie soit établie avec l'un des réseaux wifi indiqués dans la carte wifiSsidToPsk. Une fois qu'une connexion est établie, l'instance essaiera de restaurer la connexion après chaque redémarrage jusqu'à ce que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() soit appelé.

Paramètres
wifiSsidToPsk : Une carte des SSID wifi aux mots de passe.

scanSsid boolean : s'il faut rechercher les SSID masqués pour ce réseau.

Retour
boolean true si connecté au réseau wifi avec succès. false sinon

Lance
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork (String wifiSsid, 
                String wifiPsk)

Se connecte à un réseau wifi.

Active le Wi-Fi et le bloque jusqu'à ce qu'une connexion réussie soit établie avec le réseau Wi-Fi spécifié. Une fois qu'une connexion est établie, l'instance essaiera de restaurer la connexion après chaque redémarrage jusqu'à ce que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() soit appelé.

Paramètres
wifiSsid String : le ssid wifi auquel se connecter

wifiPsk String : phrase de passe PSK ou null si non chiffrée

Retour
boolean true si connecté au réseau wifi avec succès. false sinon

Lance
DeviceNotAvailableException

connectToWifiNetwork

public boolean connectToWifiNetwork ( wifiSsidToPsk)

Se connecte à un réseau wifi.

Active le wifi et bloque jusqu'à ce qu'une connexion réussie soit établie avec l'un des réseaux wifi indiqués dans la carte wifiSsidToPsk. Une fois la connexion établie, l'instance essaiera de restaurer la connexion après chaque redémarrage jusqu'à ce que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() soit appelé.f

Paramètres
wifiSsidToPsk : Une carte des SSID wifi aux mots de passe.

Retour
boolean true si connecté au réseau wifi avec succès. false sinon

Lance
DeviceNotAvailableException

connectToWifiNetwork

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

Se connecte à un réseau wifi.

Active le Wi-Fi et le bloque jusqu'à ce qu'une connexion réussie soit établie avec le réseau Wi-Fi spécifié. Une fois qu'une connexion est établie, l'instance essaiera de restaurer la connexion après chaque redémarrage jusqu'à ce que ITestDevice#disconnectFromWifi() ou ITestDevice#clearLastConnectedWifiNetwork() soit appelé.

Paramètres
wifiSsid String : le ssid wifi auquel se connecter

wifiPsk String : phrase de passe PSK ou null si non chiffrée

scanSsid boolean : s'il faut rechercher le SSID caché pour ce réseau.

Retour
boolean true si connecté au réseau wifi avec succès. false sinon

Lance
DeviceNotAvailableException

connectToWifiNetworkIfNeeded

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

Une variante de connectToWifiNetwork(String, String) qui se connecte uniquement si l'appareil n'a actuellement pas de connectivité réseau.

Paramètres
scanSsid boolean : s'il faut rechercher le SSID caché pour ce réseau

Retour
boolean true si connecté au réseau wifi avec succès. false sinon

Lance
DeviceNotAvailableException

connectToWifiNetworkIfNeeded

public boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk)

Une variante de connectToWifiNetwork(String, String) qui se connecte uniquement si l'appareil n'a actuellement pas de connectivité réseau.

Retour
boolean true si connecté au réseau wifi avec succès. false sinon

Lance
DeviceNotAvailableException

Créer un utilisateur

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

Créer un utilisateur avec un nom donné et les drapeaux fournis

Paramètres
name String : de l'utilisateur à créer sur l'appareil

guest boolean : active le drapeau utilisateur --guest lors de la création

ephemeral boolean : active le flag utilisateur --ephemeral lors de la création

Retour
int identifiant de l'utilisateur créé

Lance
DeviceNotAvailableException

Créer un utilisateur

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

Créer un utilisateur avec un nom donné et les drapeaux fournis

Paramètres
name String : de l'utilisateur à créer sur l'appareil

guest boolean : active le drapeau utilisateur --guest lors de la création

ephemeral boolean : active le flag utilisateur --ephemeral lors de la création

forTesting boolean : active le drapeau de test --for-testing lors de la création

Retour
int identifiant de l'utilisateur créé

Lance
DeviceNotAvailableException

Créer un utilisateur

public int createUser (String name)

Créez un utilisateur avec un nom donné et des drapeaux par défaut 0.

Paramètres
name String : de l'utilisateur à créer sur l'appareil

Retour
int l'entier de l'identifiant utilisateur créé

Lance
DeviceNotAvailableException

createUserNoThrow

public int createUserNoThrow (String name)

Créez un utilisateur avec un nom donné et des drapeaux par défaut 0.

Paramètres
name String : de l'utilisateur à créer sur l'appareil

Retour
int l'entier pour l'ID utilisateur créé ou -1 pour l'erreur.

Lance
DeviceNotAvailableException

supprimer le fichier

public void deleteFile (String deviceFilePath)

Méthode d'assistance pour supprimer un fichier ou un répertoire sur l'appareil.

Paramètres
deviceFilePath String : Le chemin absolu du fichier sur le périphérique.

Lance
DeviceNotAvailableException

deregisterDeviceActionReceiver

public void deregisterDeviceActionReceiver (IDeviceActionReceiver deviceActionReceiver)

Supprime le IDeviceActionReceiver enregistré.

Paramètres
deviceActionReceiver IDeviceActionReceiver : Un IDeviceActionReceiver qui sera supprimé.

deviceSoftRestarted

public boolean deviceSoftRestarted (ProcessInfo prevSystemServerProcess)

Méthode d'assistance pour vérifier si l'appareil a redémarré en douceur en comparant le system_server actuel avec le system_server précédent ProcessInfo . Utilisez getProcessByName(String) pour obtenir ProcessInfo .

Paramètres
prevSystemServerProcess ProcessInfo : le processus system_server précédent ProcessInfo .

Retour
boolean true si l'appareil a redémarré en douceur

Lance
DeviceNotAvailableException

deviceSoftRestartedSince

public boolean deviceSoftRestartedSince (long utcEpochTime, 
                TimeUnit timeUnit)

Méthode d'assistance pour vérifier si l'appareil a redémarré en douceur depuis l'heure UTC depuis l'époque de l'appareil et son ERROR(/TimeUnit) . Soft-Restart fait référence à system_server redémarré en dehors d'un redémarrage dur de l'appareil (par exemple : redémarrage demandé). Le périphérique actuel utcEpochTime en millisecondes peut être obtenu par la méthode getDeviceDate() .

Paramètres
utcEpochTime long : le temps de l'appareil en seconde depuis l'époque.

timeUnit TimeUnit : l'unité de temps TimeUnit pour le utcEpochTime donné.

Retour
boolean true si l'appareil a redémarré en douceur

Lance
DeviceNotAvailableException

désactiverAdbRoot

public boolean disableAdbRoot ()

Désactive la racine adb.

La désactivation de la racine adb peut entraîner la déconnexion de l'appareil d'adb. Cette méthode bloquera jusqu'à ce que l'appareil soit disponible.

Retour
boolean true en cas de succès.

Lance
DeviceNotAvailableException

désactiverKeyguard

public void disableKeyguard ()

Tente de désactiver le verrouillage du clavier.

Attendez d'abord que l'envoi d'entrée soit prêt, cela se produit à peu près au même moment où l'appareil signale BOOT_COMPLETE, apparemment de manière asynchrone, car l'implémentation actuelle du framework a parfois une condition de concurrence. Ensuite, la commande est envoyée pour supprimer le keyguard (fonctionne uniquement sur les non sécurisés)

Lance
DeviceNotAvailableException

désactiverNetworkMonitor

public boolean disableNetworkMonitor ()

Désactive la surveillance du réseau sur l'appareil.

Retour
boolean true si la surveillance est désactivée avec succès. false en cas d'échec.

Lance
DeviceNotAvailableException

se déconnecterduWifi

public boolean disconnectFromWifi ()

Se déconnecte d'un réseau wifi.

Supprime tous les réseaux de la liste des réseaux connus et désactive le wifi.

Retour
boolean true si déconnecté du réseau wifi avec succès. false si la déconnexion a échoué.

Lance
DeviceNotAvailableException

est-ce queFichierExiste

public boolean doesFileExist (String deviceFilePath, 
                int userId)

Méthode d'assistance pour déterminer si le fichier sur l'appareil existe pour un utilisateur donné.

Paramètres
deviceFilePath String : le chemin absolu du fichier sur l'appareil à vérifier

userId int : l'ID utilisateur par rapport auquel vérifier l'existence du fichier

Retour
boolean true si le fichier existe, false sinon.

Lance
DeviceNotAvailableException

est-ce queFichierExiste

public boolean doesFileExist (String deviceFilePath)

Méthode d'assistance pour déterminer si le fichier sur l'appareil existe.

Paramètres
deviceFilePath String : le chemin absolu du fichier sur l'appareil à vérifier

Retour
boolean true si le fichier existe, false sinon.

Lance
DeviceNotAvailableException

dumpHeap

public File dumpHeap (String process, 
                String devicePath)

Essayez de vider le tas du system_server. Il est de la responsabilité de l'appelant de nettoyer le fichier vidé.

Paramètres
process String : le nom du processus de périphérique sur lequel effectuer le dumpheap.

devicePath String : le chemin sur le périphérique où placer le dump. Il doit s'agir d'un emplacement où les autorisations le permettent.

Retour
File l' ERROR(/File) contenant le rapport. Null si quelque chose a échoué.

Lance
DeviceNotAvailableException

activerAdbRoot

public boolean enableAdbRoot ()

Active la racine adb. Si le paramètre "enable-root" est "false", enregistrera un message et reviendra sans activer root.

L'activation de la racine adb peut entraîner la déconnexion de l'appareil d'adb. Cette méthode bloquera jusqu'à ce que l'appareil soit disponible.

Retour
boolean true en cas de succès.

Lance
DeviceNotAvailableException

enableNetworkMonitor

public boolean enableNetworkMonitor ()

Active la surveillance du réseau sur l'appareil.

Retour
boolean true si la surveillance est activée avec succès. false en cas d'échec.

Lance
DeviceNotAvailableException

exécuterAdbCommand

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

Méthode d'assistance qui exécute une commande adb en tant que commande système avec un délai d'attente spécifié.

executeShellCommand(String) doit être utilisé à la place dans la mesure du possible, car cette méthode offre une meilleure détection des pannes et de meilleures performances.

Paramètres
timeout long : le temps en millisecondes avant que l'appareil ne soit considéré comme ne répondant pas, 0L pour aucun délai d'attente

cmdArgs String : la commande adb et les arguments à exécuter

Retour
String la sortie standard de la commande. null si la commande n'a pas pu s'exécuter.

Lance
DeviceNotAvailableException

exécuterAdbCommand

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

Méthode d'assistance qui exécute une commande adb en tant que commande système avec un délai d'attente spécifié.

executeShellCommand(String) doit être utilisé à la place dans la mesure du possible, car cette méthode offre une meilleure détection des pannes et de meilleures performances.

Paramètres
timeout long : le temps en millisecondes avant que l'appareil ne soit considéré comme ne répondant pas, 0L pour aucun délai d'attente

envMap : environnement à définir pour la commande

cmdArgs String : la commande adb et les arguments à exécuter

Retour
String la sortie standard de la commande. null si la commande n'a pas pu s'exécuter.

Lance
DeviceNotAvailableException

exécuterAdbCommand

public String executeAdbCommand (String... cmdArgs)

Méthode d'assistance qui exécute une commande adb en tant que commande système.

executeShellCommand(String) doit être utilisé à la place dans la mesure du possible, car cette méthode offre une meilleure détection des pannes et de meilleures performances.

Paramètres
cmdArgs String : la commande adb et les arguments à exécuter

Retour
String la sortie standard de la commande. null si la commande n'a pas pu s'exécuter.

Lance
DeviceNotAvailableException

exécuterFastbootCommand

public CommandResult executeFastbootCommand (String... cmdArgs)

Méthode d'assistance qui exécute une commande fastboot en tant que commande système avec un délai d'attente par défaut de 2 minutes.

Devrait être utilisé lorsque l'appareil est déjà en mode de démarrage rapide.

Paramètres
cmdArgs String : la commande fastboot et les arguments à exécuter

Retour
CommandResult le CommandResult contenant la sortie de la commande

Lance
DeviceNotAvailableException

exécuterFastbootCommand

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

Méthode d'assistance qui exécute une commande fastboot en tant que commande système.

Devrait être utilisé lorsque l'appareil est déjà en mode de démarrage rapide.

Paramètres
timeout long : le temps en millisecondes avant l'expiration de la commande

cmdArgs String : la commande fastboot et les arguments à exécuter

Retour
CommandResult le CommandResult contenant la sortie de la commande

Lance
DeviceNotAvailableException

executeLongFastbootCommand

public CommandResult executeLongFastbootCommand (String... cmdArgs)

Méthode d'assistance qui exécute une longue commande fastboot en tant que commande système.

Identique à executeFastbootCommand(String) sauf qu'il utilise un délai d'attente plus long.

Paramètres
cmdArgs String : la commande fastboot et les arguments à exécuter

Retour
CommandResult le CommandResult contenant la sortie de la commande

Lance
DeviceNotAvailableException

executeLongFastbootCommand

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

Méthode d'assistance qui exécute une longue commande fastboot en tant que commande système avec des variables d'environnement système.

Identique à executeFastbootCommand(String) sauf qu'il utilise un délai d'attente plus long.

Paramètres
envVarMap : les variables d'environnement système avec lesquelles la commande fastboot s'exécute

cmdArgs String : la commande fastboot et les arguments à exécuter

Retour
CommandResult le CommandResult contenant la sortie de la commande

Lance
DeviceNotAvailableException

executeShellCommand

public String executeShellCommand (String command)

Méthode d'assistance qui exécute une commande shell adb et renvoie la sortie sous la forme d'une ERROR(/String) .

Paramètres
command String : la commande shell adb à exécuter

Retour
String la sortie du shell

Lance
DeviceNotAvailableException

executeShellCommand

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

Exécute une commande shell adb, avec plus de paramètres pour contrôler le comportement de la commande.

Paramètres
command String : the adb shell command to run

receiver IShellOutputReceiver : the IShellOutputReceiver to direct shell output to.

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

timeUnit TimeUnit : unit for maxTimeToOutputShellResponse

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

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

Paramètres
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.

Lance
DeviceNotAvailableException

executeShellCommand

public void executeShellCommand (String command, 
                IShellOutputReceiver receiver)

Executes the given adb shell command, retrying multiple times if command fails.

A simpler form of executeShellCommand(String, com.android.ddmlib.IShellOutputReceiver, long, TimeUnit, int) with default values.

Paramètres
command String : the adb shell command to run

receiver IShellOutputReceiver : the IShellOutputReceiver to direct shell output to.

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

Paramètres
cmd String : The command that should be run.

Retour
CommandResult The result in CommandResult .

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

Paramètres
cmd String : The command that should be run.

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

Retour
CommandResult The result in CommandResult .

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

Paramètres
cmd String : The command that should be run.

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

Retour
CommandResult The result in CommandResult .

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

Paramètres
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.

Retour
CommandResult

Lance
DeviceNotAvailableException

executeShellV2Command

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

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

Paramètres
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

Retour
CommandResult

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

Paramètres
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.

Retour
CommandResult

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

Paramètres
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.

Retour
CommandResult

Lance
DeviceNotAvailableException

fastbootWipePartition

public CommandResult fastbootWipePartition (String partition)

Helper method which wipes a partition for the device.

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

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

Paramètres
partition String : the partition to wipe

Retour
CommandResult the CommandResult containing output of command

Lance
DeviceNotAvailableException

getActiveApexes

public  getActiveApexes ()

Fetch the information about APEXes activated on the device.

Retour
ERROR(/Set) of ApexInfo currently activated on the device

Lance
DeviceNotAvailableException

getAllSettings

public  getAllSettings (String namespace)

Return key value pairs of requested namespace.

Paramètres
namespace String : must be one of {"system", "secure", "global"}

Retour
the map of key value pairs. Null if namespace is not supported.

Lance
DeviceNotAvailableException

getAllocationState

public DeviceAllocationState getAllocationState ()

Return the current allocation state of device

Retour
DeviceAllocationState

getAndroidId

public String getAndroidId (int userId)

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

Paramètres
userId int

Retour
String

Lance
DeviceNotAvailableException

getAndroidIds

public  getAndroidIds ()

Create a Map of android ids found matching user ids. There is no insurance that each user id will found an android id associated in this function so some user ids may match null.

Retour
Map of android ids found matching user ids.

Lance
DeviceNotAvailableException

getApiLevel

public int getApiLevel ()

Get the device API Level. Defaults to UNKNOWN_API_LEVEL .

Retour
int an integer indicating the API Level of device

Lance
DeviceNotAvailableException

getAppPackageInfo

public PackageInfo getAppPackageInfo (String packageName)

Fetch information about a package installed on device.

Paramètres
packageName String

Retour
PackageInfo the PackageInfo or null if information could not be retrieved

Lance
DeviceNotAvailableException

getAppPackageInfos

public  getAppPackageInfos ()

Fetch information of packages installed on the device.

Retour
ERROR(/List) of PackageInfo s installed on the device.

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

Retour
String the ERROR(/String) baseband version or null if it cannot be determined (device has no radio or version string cannot be read)

Lance
DeviceNotAvailableException

getBattery

public Integer getBattery ()

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

Retour
Integer

getBooleanProperty

public boolean getBooleanProperty (String name, 
                boolean defaultValue)

Returns boolean value of the given property.

Paramètres
name String : the property name

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

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

Lance
DeviceNotAvailableException

getBootHistory

public  getBootHistory ()

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

Retour
Map of boot time (UTC time in second since Epoch) and boot reason

Lance
DeviceNotAvailableException

getBootHistorySince

public  getBootHistorySince (long utcEpochTime, 
                TimeUnit timeUnit)

Helper method collects the boot history map with boot time and boot reason since the given time since epoch from device and the time unit specified. The current device utcEpochTime in Millisecond can be obtained by method getDeviceDate() .

Paramètres
utcEpochTime long : the device time since Epoch.

timeUnit TimeUnit : the time unit TimeUnit .

Retour
Map of boot time (UTC time in second since Epoch) and boot reason

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

Retour
String the ERROR(/String) bootloader version or null if it cannot be found

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

Retour
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

Retour
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

Retour
String the build alias or fall back to build id if it could not be retrieved

Lance
DeviceNotAvailableException

getBuildFlavor

public String getBuildFlavor ()

Retrieve the build flavor for the device.

Retour
String the build flavor or null if it could not be retrieved

Lance
DeviceNotAvailableException

getBuildId

public String getBuildId ()

Retrieve the build the device is currently running.

Retour
String the build id or IBuildInfo#UNKNOWN_BUILD_ID if it could not be retrieved

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

Retour
String The signing key if found, null otherwise.

Lance
DeviceNotAvailableException

getCachedDeviceDescriptor

public DeviceDescriptor getCachedDeviceDescriptor ()

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

Retour
DeviceDescriptor

getCachedDeviceDescriptor

public DeviceDescriptor getCachedDeviceDescriptor (boolean shortDescriptor)

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

Paramètres
shortDescriptor boolean : Whether or not to limit descriptor to bare minimum info

Retour
DeviceDescriptor

getChildren

public String[] getChildren (String path)

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

Paramètres
path String : is the path on the device where to do the search

Retour
String[] Array of string containing all the file in a path on the device.

Lance
DeviceNotAvailableException

getConnection

public AbstractConnection getConnection ()

The current connection associated with the device.

Retour
AbstractConnection

getCurrentFoldableState

public DeviceFoldableState getCurrentFoldableState ()

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

Retour
DeviceFoldableState

Lance
DeviceNotAvailableException

getCurrentUser

public int getCurrentUser ()

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

Retour
int

Lance
DeviceNotAvailableException

getDeviceClass

public String getDeviceClass ()

Get the device class.

Retour
String the ERROR(/String) device class.

getDeviceDate

public long getDeviceDate ()

Return the date of the device in millisecond since epoch.

Retour
long the date of the device in epoch format.

Lance
DeviceNotAvailableException

getDeviceDescriptor

public DeviceDescriptor getDeviceDescriptor ()

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

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

Paramètres
shortDescriptor boolean : Whether or not to limit descriptor to bare minimum info

Retour
DeviceDescriptor

getDeviceState

public TestDeviceState getDeviceState ()

Get the device's state.

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

Paramètres
date Date

Retour
long the difference in milliseconds

Lance
DeviceNotAvailableException

getEmulatorOutput

public InputStreamSource getEmulatorOutput ()

Get the stream of emulator stdout and stderr

Retour
InputStreamSource emulator output

getEmulatorProcess

public Process getEmulatorProcess ()

Return the ERROR(/Process) corresponding to this emulator.

Retour
Process the ERROR(/Process) or null

getExecuteShellCommandLog

public final File getExecuteShellCommandLog ()

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

Retour
File

getExternalStoreFreeSpace

public long getExternalStoreFreeSpace ()

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

Retour
long the amount of free space in KB

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

Retour
String

getFastbootProductType

public String getFastbootProductType ()

Convenience method to get the product type of this device when its in fastboot mode.

This method should only be used if device should be in fastboot. Its a bit safer variant than the generic getProductType() method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.

Retour
String the ERROR(/String) product type name or null if it cannot be determined

Lance
DeviceNotAvailableException

getFastbootProductVariant

public String getFastbootProductVariant ()

Convenience method to get the product type of this device when its in fastboot mode.

This method should only be used if device should be in fastboot. Its a bit safer variant than the generic getProductType() method in this case, because ITestDevice will know to recover device into fastboot if device is in incorrect state or is unresponsive.

Retour
String the ERROR(/String) product type name or null if it cannot be determined

Lance
DeviceNotAvailableException

getFastbootSerialNumber

public String getFastbootSerialNumber ()

Returns the fastboot mode serial number.

Retour
String

getFastbootVariable

public String getFastbootVariable (String variableName)

Retrieve the given fastboot variable value from the device.

Paramètres
variableName String : the variable name

Retour
String the property value or null if it does not exist

Lance
DeviceNotAvailableException

getFastbootVersion

public String getFastbootVersion ()

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

Retour
String

getFileEntry

public IFileEntry getFileEntry (String path)

Retrieve a reference to a remote file on device.

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

Retour
IFileEntry the IFileEntry or null if file at given path cannot be found

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

Paramètres
entry FileListingService.FileEntry : a FileEntry not necessarily root as Ddmlib requires.

Retour
IFileEntry a FileEntryWrapper representing the FileEntry.

Lance
com.android.tradefed.device.DeviceNotAvailableException
DeviceNotAvailableException

getFoldableStates

public  getFoldableStates ()

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

Retour

Lance
DeviceNotAvailableException

getIDevice

public IDevice getIDevice ()

Returns a reference to the associated ddmlib IDevice .

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

Retour
IDevice the IDevice

getInstalledPackageNames

public  getInstalledPackageNames ()

Fetch the application package names present on the device.

Retour
ERROR(/Set) of ERROR(/String) package names currently installed on the device.

Lance
DeviceNotAvailableException

getIntProperty

public long getIntProperty (String name, 
                long defaultValue)

Returns integer value of the given property from the device.

Paramètres
name String : the property name

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

Retour
long the property value or defaultValue if the property is empty, doesn't exist, or doesn't have an integer value.

Lance
DeviceNotAvailableException

getIpAddress

public String getIpAddress ()

Gets the device's IP address.

Retour
String the device's IP address, or null if device has no IP address

Lance
DeviceNotAvailableException

getKeyguardState

public KeyguardControllerState getKeyguardState ()

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

Retour
KeyguardControllerState a KeyguardControllerState containing a snapshot of the state of the keyguard and returns Null if the Keyguard query is not supported.

Lance
DeviceNotAvailableException

getLastExpectedRebootTimeMillis

public long getLastExpectedRebootTimeMillis ()

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

Retour
long

getLaunchApiLevel

public int getLaunchApiLevel ()

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

Retour
int an integer indicating the first launched API Level of device

Lance
DeviceNotAvailableException

getLogcat

public InputStreamSource getLogcat ()

Grabs a snapshot stream of the logcat data.

Works in two modes:

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

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

    Paramètres
    maxBytes int : the maximum amount of data to return. Should be an amount that can comfortably fit in memory

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

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

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

    Retour
    InputStreamSource

    getMacAddress

    public String getMacAddress ()

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

    Retour
    String

    getMainUserId

    public Integer getMainUserId ()

    Returns the main user id.

    Retour
    Integer the userId of the main user if there is one, and null if there is no main user.

    Lance
    DeviceNotAvailableException

    getMainlineModuleInfo

    public  getMainlineModuleInfo ()

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

    Retour
    ERROR(/Set) of ERROR(/String) mainline modules currently installed on the device.

    Lance
    DeviceNotAvailableException

    getMaxNumberOfRunningUsersSupported

    public int getMaxNumberOfRunningUsersSupported ()

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

    Retour
    int an integer indicating the number of simultaneously running users

    Lance
    DeviceNotAvailableException

    getMaxNumberOfUsersSupported

    public int getMaxNumberOfUsersSupported ()

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

    Retour
    int an integer indicating the number of supported users

    Lance
    DeviceNotAvailableException

    getMicrodroidProcess

    public Process getMicrodroidProcess ()

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

    Retour
    IDeviceStateMonitor

    getMountPoint

    public String getMountPoint (String mountName)

    Returns a mount point.

    Queries the device directly if the cached info in IDevice is not available.

    TODO: move this behavior to IDevice#getMountPoint(String)

    Paramètres
    mountName String : the name of the mount point

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

    Paramètres
    mountpoint String

    Retour
    ITestDevice.MountPointInfo A ERROR(/List) of MountPointInfo containing the information in "/proc/mounts"

    Lance
    DeviceNotAvailableException

    getMountPointInfo

    public  getMountPointInfo ()

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

    Retour
    A ERROR(/List) of MountPointInfo containing the information in "/proc/mounts"

    Lance
    DeviceNotAvailableException

    getOptions

    public TestDeviceOptions getOptions ()

    Fetch the test options for the device.

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

    Paramètres
    partition String

    Retour
    long the amount of free space in KB

    Lance
    DeviceNotAvailableException

    getPrimaryUserId

    public Integer getPrimaryUserId ()

    Returns the primary user id.

    Retour
    Integer the userId of the primary user if there is one, and null if there is no primary user.

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

    Paramètres
    processName String : the proces name String.

    Retour
    ProcessInfo ProcessInfo of given processName

    Lance
    DeviceNotAvailableException

    getProcessPid

    public String getProcessPid (String process)

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

    Paramètres
    process String : The proces name String.

    Retour
    String

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

    Retour
    String the ERROR(/String) product type name. Will not be null

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

    Retour
    String the ERROR(/String) product variant name or null if it cannot be determined

    Lance
    DeviceNotAvailableException

    getProperty

    public String getProperty (String name)

    Retrieve the given property value from the device.

    Paramètres
    name String : the property name

    Retour
    String the property value or null if it does not exist

    Lance
    DeviceNotAvailableException

    getRecoveryMode

    public ITestDevice.RecoveryMode getRecoveryMode ()

    Get the current recovery mode used for the device.

    Retour
    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

    Paramètres
    format String : supported PNG, JPEG

    Retour
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

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

    Paramètres
    displayId long : the display id of the screen to get screenshot from.

    Retour
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

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

    Paramètres
    format String : supported PNG, JPEG

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

    Retour
    InputStreamSource a InputStreamSource of the screenshot in format, or null if the screenshot was not successful.

    Lance
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot ()

    Grabs a screenshot from the device.

    Retour
    InputStreamSource a InputStreamSource of the screenshot in png format, or null if the screenshot was not successful.

    Lance
    DeviceNotAvailableException

    getSerialNumber

    public String getSerialNumber ()

    Convenience method to get serial number of this device.

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

    Paramètres
    userId int

    namespace String

    key String

    Retour
    String the value associated with the namespace:key of a user. Null if not found.

    Lance
    DeviceNotAvailableException

    getSetting

    public String getSetting (String namespace, 
                    String key)

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

    Paramètres
    namespace String

    key String

    Retour
    String

    Lance
    DeviceNotAvailableException

    getSimOperator

    public String getSimOperator ()

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

    Retour
    String

    getSimState

    public String getSimState ()

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

    Retour
    String

    getTombstones

    public  getTombstones ()

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

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

    Retour
    A list of tombstone files, empty if no tombstone.

    Lance
    DeviceNotAvailableException

    getTotalMemory

    public long getTotalMemory ()

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

    Retour
    long

    getUninstallablePackageNames

    public  getUninstallablePackageNames ()

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

    Retour
    ERROR(/Set) of uninstallable ERROR(/String) package names currently installed on the device.

    Lance
    DeviceNotAvailableException

    getUseFastbootErase

    public boolean getUseFastbootErase ()

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

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

    Paramètres
    userId int

    Retour
    int the flags associated with the userId provided if found, -10000 in any other cases.

    Lance
    DeviceNotAvailableException

    getUserInfos

    public  getUserInfos ()

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

    Retour
    the list of UserInfo objects.

    Lance
    DeviceNotAvailableException

    getUserSerialNumber

    public int getUserSerialNumber (int userId)

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

    Paramètres
    userId int

    Retour
    int

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

    Paramètres
    event DeviceEvent

    Retour
    IManagedTestDevice.DeviceEventResponse

    hasFeature

    public boolean hasFeature (String feature)

    Check if a feature is available on a device.

    Paramètres
    feature String : which format should be "feature: " or " " directly.

    Retour
    boolean True if feature is found, false otherwise.

    Lance
    DeviceNotAvailableException

    installPackage

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

    Install an Android package on device.

    Paramètres
    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.

    Retour
    String a ERROR(/String) with an error code, or null if success.

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

    Paramètres
    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.

    Retour
    String a ERROR(/String) with an error code, or null if success.

    Lance
    DeviceNotAvailableException

    installPackageForUser

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

    Install an Android package on device for a given user.

    Paramètres
    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.

    Retour
    String a ERROR(/String) with an error code, or null if success.

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

    Paramètres
    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.

    Retour
    String a ERROR(/String) with an error code, or null if success.

    Lance
    DeviceNotAvailableException

    invalidatePropertyCache

    public void invalidatePropertyCache ()

    isAdbRoot

    public boolean isAdbRoot ()

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    isAdbTcp

    public boolean isAdbTcp ()

    Retour
    boolean

    isAppEnumerationSupported

    public boolean isAppEnumerationSupported ()

    Check whether platform on device supports app enumeration

    Retour
    boolean True if app enumeration is supported, false otherwise

    Lance
    DeviceNotAvailableException

    isBypassLowTargetSdkBlockSupported

    public boolean isBypassLowTargetSdkBlockSupported ()

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

    Retour
    boolean True if bypass low target sdk block is supported, false otherwise

    Lance
    DeviceNotAvailableException

    isDeviceEncrypted

    public boolean isDeviceEncrypted ()

    Returns if the device is encrypted.

    Retour
    boolean true if the device is encrypted.

    Lance
    DeviceNotAvailableException

    isDirectory

    public boolean isDirectory (String path)

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

    Paramètres
    path String

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    isEnableAdbRoot

    public boolean isEnableAdbRoot ()

    Retour
    boolean true if adb root should be enabled on device

    isEncryptionSupported

    public boolean isEncryptionSupported ()

    Returns if encryption is supported on the device.

    Retour
    boolean true if the device supports encryption.

    Lance
    DeviceNotAvailableException

    isExecutable

    public boolean isExecutable (String fullPath)

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

    Paramètres
    fullPath String

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    isFastbootEnabled

    public boolean isFastbootEnabled ()

    Return if fastboot is available for the device.

    Retour
    boolean

    isHeadless

    public boolean isHeadless ()

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

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    isHeadlessSystemUserMode

    public boolean isHeadlessSystemUserMode ()

    Returns whether the device uses headless system user mode.

    Retour
    boolean

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

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    isMultiUserSupported

    public boolean isMultiUserSupported ()

    Determines if multi user is supported.

    Retour
    boolean true if multi user is supported, false otherwise

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

    Paramètres
    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.

    Retour
    boolean True if the package is reported as installed. False otherwise.

    Lance
    DeviceNotAvailableException

    isPackageInstalled

    public boolean isPackageInstalled (String packageName)

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

    Paramètres
    packageName String

    Retour
    boolean True if the package is reported as installed. False otherwise.

    Lance
    DeviceNotAvailableException

    isRuntimePermissionSupported

    public boolean isRuntimePermissionSupported ()

    Check whether platform on device supports runtime permission granting

    Retour
    boolean True if runtime permission are supported, false otherwise.

    Lance
    DeviceNotAvailableException

    isStateBootloaderOrFastbootd

    public boolean isStateBootloaderOrFastbootd ()

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

    Retour
    boolean

    isUserRunning

    public boolean isUserRunning (int userId)

    Check if a given user is running.

    Paramètres
    userId int

    Retour
    boolean True if the user is running, false in every other cases.

    Lance
    DeviceNotAvailableException

    isUserSecondary

    public boolean isUserSecondary (int userId)

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

    Paramètres
    userId int

    Retour
    boolean true if the user is secondary, false otherwise.

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

    Paramètres
    userId int

    Retour
    boolean

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

    Paramètres
    userId int

    displayId int

    Retour
    boolean

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

    Retour
    boolean

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

    Retour
    boolean

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

    Retour
    boolean true if wifi is enabled. false if disabled

    Lance
    DeviceNotAvailableException

    listDisplayIds

    public  listDisplayIds ()

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

    Retour
    The list of displays. Default always returns the default display 0.

    Lance
    DeviceNotAvailableException

    listDisplayIdsForStartingVisibleBackgroundUsers

    public  listDisplayIdsForStartingVisibleBackgroundUsers ()

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

    Retour

    Lance
    DeviceNotAvailableException

    listUsers

    public  listUsers ()

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

    Retour
    the list of user ids.

    Lance
    DeviceNotAvailableException

    logAnrs

    public boolean logAnrs (ITestLogger logger)

    Collects and log ANRs from the device.

    Paramètres
    logger ITestLogger : an ITestLogger to log the ANRs.

    Retour
    boolean True if the logging was successful, false otherwise.

    Lance
    DeviceNotAvailableException

    logBugreport

    public boolean logBugreport (String dataName, 
                    ITestLogger listener)

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

    Paramètres
    dataName String : name under which the bugreport will be reported.

    listener ITestLogger : an ITestLogger to log the bugreport.

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

    Paramètres
    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.

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

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

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

    Lance
    DeviceNotAvailableException

    postInvocationTearDown

    public void postInvocationTearDown (Throwable exception)

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

    Paramètres
    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.

    Paramètres
    info IBuildInfo : The IBuildInfo of the device.

    attributes MultiMap : The attributes stored in the invocation context

    Lance
    DeviceNotAvailableException
    TargetSetupError

    pullDir

    public boolean pullDir (String deviceFilePath, 
                    File localDir)

    Recursively pull directory contents from device.

    Paramètres
    deviceFilePath String : the absolute file path of the remote source

    localDir File : the local directory to pull files into

    Retour
    boolean true if file was pulled successfully. false otherwise.

    Lance
    DeviceNotAvailableException

    pullFile

    public boolean pullFile (String remoteFilePath, 
                    File localFile)

    Retrieves a file off device.

    Paramètres
    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.

    Retour
    boolean true if file was retrieved successfully. false otherwise.

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

    Paramètres
    remoteFilePath String : the absolute path to file on device.

    userId int : The user id to pull from

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

    Lance
    DeviceNotAvailableException

    pullFile

    public File pullFile (String remoteFilePath)

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

    Paramètres
    remoteFilePath String : the absolute path to file on device.

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

    Lance
    DeviceNotAvailableException

    pullFile

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

    Retrieves a file off device.

    Paramètres
    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

    Retour
    boolean true if file was retrieved successfully. false otherwise.

    Lance
    DeviceNotAvailableException

    pullFileContents

    public String pullFileContents (String remoteFilePath)

    Retrieves a file off device, and returns the contents.

    Paramètres
    remoteFilePath String : the absolute path to file on device.

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

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

    Paramètres
    remoteFilePath String : the path to file on device, relative to the device's external storage mountpoint

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

    Lance
    DeviceNotAvailableException

    pushDir

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

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

    Paramètres
    localFileDir File : the local directory to push

    deviceFilePath String : the absolute file path of the remote destination

    excludedDirectories : Set of excluded directories names that shouldn't be pushed.

    Retour
    boolean true if file was pushed successfully. false otherwise.

    Lance
    DeviceNotAvailableException

    pushDir

    public boolean pushDir (File localFileDir, 
                    String deviceFilePath)

    Recursively push directory contents to device.

    Paramètres
    localFileDir File : the local directory to push

    deviceFilePath String : the absolute file path of the remote destination

    Retour
    boolean true if file was pushed successfully. false otherwise.

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

    Paramètres
    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

    Retour
    boolean true if file was pushed successfully. false otherwise.

    Lance
    DeviceNotAvailableException

    pushFile

    public boolean pushFile (File localFile, 
                    String remoteFilePath)

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

    Paramètres
    localFile File : the local file to push

    remoteFilePath String : the remote destination absolute file path

    Retour
    boolean true if file was pushed successfully. false otherwise.

    Lance
    DeviceNotAvailableException

    pushString

    public boolean pushString (String contents, 
                    String remoteFilePath)

    Push file created from a string to device

    Paramètres
    contents String : the contents of the file to push

    remoteFilePath String : the remote destination absolute file path

    Retour
    boolean true if string was pushed successfully. false otherwise.

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

    Paramètres
    reason String : a reason for this reboot, or null if no reason is specified.

    Lance
    DeviceNotAvailableException

    reboot

    public void reboot ()

    Reboots the device into adb mode.

    Blocks until device becomes available.

    Lance
    DeviceNotAvailableException

    rebootIntoBootloader

    public void rebootIntoBootloader ()

    Reboots the device into bootloader mode.

    Blocks until device is in bootloader mode.

    Lance
    DeviceNotAvailableException

    rebootIntoFastbootd

    public void rebootIntoFastbootd ()

    Reboots the device into fastbootd mode.

    Blocks until device is in fastbootd mode.

    Lance
    DeviceNotAvailableException

    rebootIntoRecovery

    public void rebootIntoRecovery ()

    Reboots the device into adb recovery mode.

    Blocks until device enters recovery

    Lance
    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

    Lance
    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

    Paramètres
    autoReboot boolean : whether to automatically reboot the device after sideload

    Lance
    DeviceNotAvailableException

    rebootUntilOnline

    public void rebootUntilOnline ()

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

    Lance
    DeviceNotAvailableException

    rebootUntilOnline

    public void rebootUntilOnline (String reason)

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

    Paramètres
    reason String : a reason for this reboot, or null if no reason is specified.

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

    Lance
    DeviceNotAvailableException

    rebootUserspaceUntilOnline

    public void rebootUserspaceUntilOnline ()

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

    Lance
    DeviceNotAvailableException

    recoverDevice

    public boolean recoverDevice ()

    Attempts to recover device communication.

    Retour
    boolean True if recovery attempted and successful, returns False if recovery was skipped

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

    Paramètres
    deviceActionReceiver IDeviceActionReceiver : A IDeviceActionReceiver which will be registered.

    remountSystemWritable

    public void remountSystemWritable ()

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

    Lance
    DeviceNotAvailableException

    remountVendorWritable

    public void remountVendorWritable ()

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

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

    Paramètres
    componentName String : of device admin to be removed.

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

    Retour
    boolean True if it is successful, false otherwise.

    Lance
    DeviceNotAvailableException

    removeOwners

    public void removeOwners ()

    Remove all existing device profile owners with the best effort.

    Lance
    DeviceNotAvailableException

    removeUser

    public boolean removeUser (int userId)

    Remove a given user from the device.

    Paramètres
    userId int : of the user to remove

    Retour
    boolean true if we were successful in removing the user, false otherwise.

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

    Paramètres
    runner IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests

    listeners ITestLifeCycleReceiver : the test result listener(s)

    Retour
    boolean true if test command completed. false if it failed to complete, but recovery succeeded

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

    Paramètres
    runner IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests

    listeners : the test result listeners

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

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

    Paramètres
    runner IRemoteAndroidTestRunner

    userId int

    listeners

    Retour
    boolean

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

    Paramètres
    runner IRemoteAndroidTestRunner

    userId int

    listeners ITestLifeCycleReceiver

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    setConfiguration

    public void setConfiguration (IConfiguration configuration)

    Injects the IConfiguration in use.

    Paramètres
    configuration IConfiguration

    setDate

    public void setDate (Date date)

    Sets the date on device

    Note: setting date on device requires root

    Paramètres
    date Date : specify a particular date; will use host date if null

    Lance
    DeviceNotAvailableException

    setDeviceOwner

    public boolean setDeviceOwner (String componentName, 
                    int userId)

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

    Paramètres
    componentName String : of device admin to be device owner.

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

    Retour
    boolean True if it is successful, false otherwise.

    Lance
    DeviceNotAvailableException

    setDeviceState

    public void setDeviceState (TestDeviceState deviceState)

    Update the device's state.

    Paramètres
    deviceState TestDeviceState : the TestDeviceState

    setEmulatorOutputStream

    public void setEmulatorOutputStream (SizeLimitedOutputStream output)

    For emulator set SizeLimitedOutputStream to log output

    Paramètres
    output SizeLimitedOutputStream : to log the output

    setEmulatorProcess

    public void setEmulatorProcess (Process p)

    Sets the ERROR(/Process) , when this device is an emulator.

    Paramètres
    p Process

    setFastbootEnabled

    public void setFastbootEnabled (boolean fastbootEnabled)

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

    Paramètres
    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.

    Paramètres
    fastbootPath String

    setIDevice

    public void setIDevice (IDevice newDevice)

    Update the IDevice associated with this ITestDevice.

    The new IDevice must refer the same physical device as the current reference. This method will be called if DDMS has allocated a new IDevice

    Paramètres
    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.

    Paramètres
    delay int : the delay in ms

    setOptions

    public void setOptions (TestDeviceOptions options)

    Set the TestDeviceOptions for the device

    Paramètres
    options TestDeviceOptions

    setProperty

    public boolean setProperty (String propKey, 
                    String propValue)

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

    Paramètres
    propKey String : The key targeted to be set.

    propValue String : The property value to be set.

    Retour
    boolean returns True if the setprop command was successful, False otherwise.

    Lance
    DeviceNotAvailableException

    setRecovery

    public void setRecovery (IDeviceRecovery recovery)

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

    Paramètres
    recovery IDeviceRecovery : the IDeviceRecovery

    setRecoveryMode

    public void setRecoveryMode (ITestDevice.RecoveryMode mode)

    Set the current recovery mode to use for the device.

    Used to control what recovery method to use when a device communication problem is encountered. Its recommended to only use this method sparingly when needed (for example, when framework is down, etc

    Paramètres
    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.

    Paramètres
    namespace String

    key String

    value String

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

    Paramètres
    userId int

    namespace String

    key String

    value String

    Lance
    DeviceNotAvailableException

    setTestLogger

    public void setTestLogger (ITestLogger testLogger)

    Injects the ITestLogger instance

    Paramètres
    testLogger ITestLogger

    setUseFastbootErase

    public void setUseFastbootErase (boolean useFastbootErase)

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

    Paramètres
    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.

    Paramètres
    userId int : of the user to start in the background

    Retour
    boolean true if the user was successfully started in the background.

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

    Paramètres
    userId int : of the user to start in the background

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

    Retour
    boolean true if the user was successfully started in the background.

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

    Paramètres
    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.

    Retour
    boolean true if the user was successfully started visible in the background.

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

    Paramètres
    userId int : of the user to stop.

    Retour
    boolean true if the user was successfully stopped.

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

    Paramètres
    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.

    Retour
    boolean true if the user was successfully stopped.

    Lance
    DeviceNotAvailableException

    switchToAdbTcp

    public String switchToAdbTcp ()

    Switch device to adb-over-tcp mode.

    Retour
    String the tcp serial number or null if device could not be switched

    Lance
    DeviceNotAvailableException

    switchToAdbUsb

    public boolean switchToAdbUsb ()

    Switch device to adb over usb mode.

    Retour
    boolean true if switch was successful, false otherwise.

    Lance
    DeviceNotAvailableException

    switchUser

    public boolean switchUser (int userId)

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

    Paramètres
    userId int

    Retour
    boolean True if the new userId matches the userId provider. False otherwise.

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

    Paramètres
    userId int

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

    Retour
    boolean True if the new userId matches the userId provider. False otherwise.

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

    Paramètres
    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

    Retour
    boolean true if files were synced successfully. false otherwise.

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

    Retour
    Bugreport

    uninstallPackage

    public String uninstallPackage (String packageName)

    Uninstall an Android package from device.

    Paramètres
    packageName String : the Android package to uninstall

    Retour
    String a ERROR(/String) with an error code, or null if success.

    Lance
    DeviceNotAvailableException

    uninstallPackageForUser

    public String uninstallPackageForUser (String packageName, 
                    int userId)

    Uninstall an Android package from device for a given user.

    Paramètres
    packageName String : the Android package to uninstall

    userId int : the integer user id to uninstall for.

    Retour
    String a ERROR(/String) with an error code, or null if success.

    Lance
    DeviceNotAvailableException

    unlockDevice

    public boolean unlockDevice ()

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

    This method may restart the framework but will not call postBootSetup() . Therefore, the device might not be fully ready to be tested when this method returns.

    Retour
    boolean true if successful or if the device is unencrypted.

    Lance
    DeviceNotAvailableException

    waitForBootComplete

    public boolean waitForBootComplete (long timeOut)

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

    Paramètres
    timeOut long : time in msecs to wait for the flag to be set

    Retour
    boolean true if device's boot complete flag is set within the timeout

    Lance
    DeviceNotAvailableException

    waitForDeviceAvailable

    public boolean waitForDeviceAvailable ()

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

    Retour
    boolean True if device is available, False if recovery is disabled and unavailable.

    Lance
    DeviceNotAvailableException

    waitForDeviceAvailable

    public boolean waitForDeviceAvailable (long waitTime)

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

    Paramètres
    waitTime long : the time in ms to wait

    Retour
    boolean True if device is available, False if recovery is disabled and unavailable.

    Lance
    DeviceNotAvailableException

    waitForDeviceAvailableInRecoverPath

    public boolean waitForDeviceAvailableInRecoverPath (long waitTime)

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

    Paramètres
    waitTime long

    Retour
    boolean True if device is available, False if unavailable.

    Lance
    DeviceNotAvailableException

    waitForDeviceBootloader

    public void waitForDeviceBootloader ()

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

    Lance
    DeviceNotAvailableException

    waitForDeviceInRecovery

    public boolean waitForDeviceInRecovery (long waitTime)

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

    Paramètres
    waitTime long : the time in ms to wait

    Retour
    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

    Paramètres
    waitTime long : the time in ms to wait

    Retour
    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

    Paramètres
    waitTime long : the time in ms to wait

    Retour
    boolean true if device becomes not available before time expires. false otherwise

    waitForDeviceOnline

    public void waitForDeviceOnline ()

    Blocks until device is visible via adb. Uses default timeout

    Note the device may not necessarily be responsive to commands on completion. Use waitForDeviceAvailable() instead.

    Lance
    DeviceNotAvailableException

    waitForDeviceOnline

    public void waitForDeviceOnline (long waitTime)

    Blocks until device is visible via adb.

    Note the device may not necessarily be responsive to commands on completion. Use waitForDeviceAvailable() instead.

    Paramètres
    waitTime long : the time in ms to wait

    Lance
    DeviceNotAvailableException

    waitForDeviceShell

    public boolean waitForDeviceShell (long waitTime)

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

    Paramètres
    waitTime long : the time in ms to wait

    Retour
    boolean true if device becomes responsive before waitTime elapses.

    Protected methods

    addExtraConnectionBuilderArgs

    protected void addExtraConnectionBuilderArgs (DefaultConnection.ConnectionBuilder builder)

    Paramètres
    builder DefaultConnection.ConnectionBuilder

    buildAdbShellCommand

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

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

    Paramètres
    command String

    forceExitStatusDetection boolean

    Retour
    String[]

    checkApiLevelAgainst

    protected void checkApiLevelAgainst (String feature, 
                    int strictMinLevel)

    Paramètres
    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.

    Paramètres
    rebootMode NativeDevice.RebootMode : a mode of this reboot.

    reason String : for this reboot.

    Retour
    NativeDevice.RebootDeviceAction the created RebootDeviceAction .

    createRunUtil

    protected IRunUtil createRunUtil ()

    Retour
    IRunUtil

    doAdbReboot

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

    Perform a adb reboot.

    Paramètres
    rebootMode NativeDevice.RebootMode : a mode of this reboot.

    reason String : for this reboot.

    Lance
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    ensureRuntimePermissionSupported

    protected void ensureRuntimePermissionSupported ()

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

    Lance
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    getApiLevelSafe

    protected int getApiLevelSafe ()

    Retour
    int

    getLogger

    protected ITestLogger getLogger ()

    Retour
    ITestLogger

    getRunUtil

    protected IRunUtil getRunUtil ()

    Get the RunUtil instance to use.

    Retour
    IRunUtil

    initializeConnection

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

    Paramètres
    info IBuildInfo

    attributes MultiMap

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

    Paramètres
    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.

    Retour
    String A string, possibly null or empty, containing the value of the given property

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

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

    Paramètres
    localFile File

    entry IFileEntry

    Retour
    boolean

    notifyRebootEnded

    protected void notifyRebootEnded ()

    Notifies all IDeviceActionReceiver about reboot end event.

    Lance
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    notifyRebootStarted

    protected void notifyRebootStarted ()

    Notifies all IDeviceActionReceiver about reboot start event.

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

    Paramètres
    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

    Retour
    boolean true if action was performed successfully

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

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

    Lance
    com.android.tradefed.device.DeviceNotAvailableException
    DeviceNotAvailableException

    pullFileInternal

    protected boolean pullFileInternal (String remoteFilePath, 
                    File localFile)

    Paramètres
    remoteFilePath String

    localFile File

    Retour
    boolean

    Lance
    DeviceNotAvailableException

    setClock

    protected void setClock (Clock clock)

    Set the Clock instance to use.

    Paramètres
    clock Clock

    setMicrodroidProcess

    protected void setMicrodroidProcess (Process process)

    Marks the TestDevice as microdroid and sets its CID.

    Paramètres
    process Process : Process of the Microdroid VM.

    setTestDeviceOptions

    protected void setTestDeviceOptions ( deviceOptions)

    Paramètres
    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.

    Paramètres
    timeout long

    envVarMap

    fullCmd String

    Retour
    CommandResult

    simpleFastbootCommand

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

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

    Paramètres
    timeout long

    fullCmd String

    Retour
    CommandResult

    waitForDeviceNotAvailable

    protected boolean waitForDeviceNotAvailable (String operationDesc, 
                    long time)

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

    Paramètres
    operationDesc String : The name of the operation that is waiting for unavailable.

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

    Retour
    boolean True if device did become unavailable.