Google致力於提高黑人社區的種族平等。 怎麼看。
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

本機設備

public class NativeDevice
extends Object implements IManagedTestDevice

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


ITestDevice默認實現非全棧android設備。

摘要

嵌套類

class NativeDevice.AdbAction

DeviceAction用於運行操作系統“ adb ....”命令。

class NativeDevice.AdbShellAction

class NativeDevice.RebootDeviceAction

用於重新啟動設備的DeviceAction

常數

int INVALID_USER_ID

對於任何無效/未找到的用戶ID返回的值:UserHandle定義了-10000值

long MAX_HOST_DEVICE_TIME_OFFSET

int MAX_RETRY_ATTEMPTS

默認的命令重試嘗試次數

領域

protected TestDeviceOptions mOptions

protected final IDeviceStateMonitor mStateMonitor

公共建設者

NativeDevice (IDevice device, IDeviceStateMonitor stateMonitor, IDeviceMonitor allocationMonitor)

創建一個TestDevice

公開方法

boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

在最低支持級別下,檢查當前是否支持某個功能。

boolean checkConnectivity ()

檢查設備是否具有網絡連接。

boolean clearErrorDialogs ()

嘗試關閉設備界面上當前顯示的所有錯誤對話框。

void clearLastConnectedWifiNetwork ()

清除最後連接的wifi網絡。

void clearLogcat ()

刪除任何累積的logcat數據。

boolean connectToWifiNetwork (String wifiSsid, String wifiPsk)

連接到wifi網絡。

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

連接到wifi網絡。

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

connectToWifiNetwork(String, String)變體,僅在設備當前沒有網絡連接時才連接。

boolean connectToWifiNetworkIfNeeded (String wifiSsid, String wifiPsk)

connectToWifiNetwork(String, String)變體,僅在設備當前沒有網絡連接時才連接。

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

創建具有給定名稱和提供的標誌的用戶

int createUser (String name)

創建一個具有給定名稱和默認標誌0的用戶。

int createUserNoThrow (String name)

創建一個具有給定名稱和默認標誌0的用戶。

void deleteFile (String deviceFilePath)

刪除設備上文件或目錄的幫助方法。

boolean disableAdbRoot ()

關閉adb根目錄。

void disableKeyguard ()

嘗試禁用鍵盤鎖。

boolean disableNetworkMonitor ()

在設備上禁用網絡監視。

boolean disconnectFromWifi ()

斷開與wifi網絡的連接。

boolean doesFileExist (String deviceFilePath)

確定設備上文件是否存在的輔助方法。

File dumpHeap (String process, String devicePath)

嘗試從system_server中轉儲堆。

boolean enableAdbRoot ()

打開adb根目錄。

boolean enableNetworkMonitor ()

在設備上啟用網絡監視。

boolean encryptDevice (boolean inplace)

加密設備。

String executeAdbCommand (String... cmdArgs)

將adb命令作為系統命令執行的Helper方法。

CommandResult executeFastbootCommand (String... cmdArgs)

幫助程序方法,將fastboot命令作為系統命令執行,默認超時為2分鐘。

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

將fastboot命令作為系統命令執行的Helper方法。

CommandResult executeLongFastbootCommand (String... cmdArgs)

將長時間運行的fastboot命令作為系統命令執行的Helper方法。

String executeShellCommand (String command)

執行adb shell命令並以String返回輸出的Helper方法。

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

執行adb shell命令,並使用更多參數來控制命令行為。

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

執行adb shell命令,並使用更多參數來控制命令行為。

void executeShellCommand (String command, IShellOutputReceiver receiver)

執行給定的adb shell命令,如果命令失敗,則重試多次。

CommandResult executeShellV2Command (String cmd)

Helper方法,該方法執行adb shell命令,並將結果作為CommandResult返回,並正確填充命令狀態輸出stdout和stderr。

CommandResult executeShellV2Command (String cmd, OutputStream pipeToOutput)

Helper方法,該方法執行adb shell命令,並將結果作為CommandResult返回,並正確填充命令狀態輸出stdout和stderr。

CommandResult executeShellV2Command (String cmd, File pipeAsInput)

Helper方法,該方法執行adb shell命令,並將結果作為CommandResult返回,並正確填充命令狀態輸出stdout和stderr。

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

執行adb shell命令,並使用更多參數來控制命令行為。

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

執行adb shell命令,並使用更多參數來控制命令行為。

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

執行adb shell命令,並使用更多參數來控制命令行為。

CommandResult fastbootWipePartition (String partition)

擦除設備分區的輔助方法。

getActiveApexes ()

獲取有關在設備上激活的APEX的信息。

getAllSettings (String namespace)

返回請求的名稱空間的鍵值對。

DeviceAllocationState getAllocationState ()

返回設備的當前分配狀態

String getAndroidId (int userId)

查找並返回與userId關聯的android-id,如果未找到,則返回null。

getAndroidIds ()

創建一個與用戶ID匹配的android ID映射。

int getApiLevel ()

獲取設備API級別。

PackageInfo getAppPackageInfo (String packageName)

獲取有關設備上安裝的軟件包的信息。

String getBasebandVersion ()

獲取此設備的基帶(無線電)版本的便捷方法。

Integer getBattery ()

返回設備的當前電池電量;如果電池電量不可用,則返回Null。

String getBootloaderVersion ()

獲取此設備的引導程序版本的便捷方法。

InputStreamSource getBugreport ()

從設備檢索錯誤報告。

InputStreamSource getBugreportz ()

從設備檢索錯誤報告。

String getBuildAlias ()

檢索設備當前正在運行的內部版本的別名。

String getBuildFlavor ()

檢索設備的構建味道。

String getBuildId ()

檢索設備當前正在運行的版本。

String getBuildSigningKeys ()

返回用於簽署設備映像的密鑰類型

通常,Android設備可能會使用測試鍵(如AOSP中的簽名)或釋放鍵(由各個設備製造商控制)進行簽名

String[] getChildren (String path)

替代使用IFileEntry ,由於權限的IFileEntry ,有時無法使用。

int getCurrentUser ()

返回當前運行用戶的ID。

String getDeviceClass ()

獲取設備類。

long getDeviceDate ()

返回設備的日期,以毫秒為單位。

DeviceDescriptor getDeviceDescriptor ()

從設備信息返回DeviceDescriptor以獲取有關它的信息,而無需傳遞實際的設備對象。

TestDeviceState getDeviceState ()

獲取設備的狀態。

long getDeviceTimeOffset (Date date)

幫助程序獲取設備與給定ERROR(/Date)之間的時間差。

InputStreamSource getEmulatorOutput ()

獲取模擬器stdout和stderr的流

Process getEmulatorProcess ()

返回與此模擬器對應的Process

final File getExecuteShellCommandLog ()

包含所有executeShellCommand(String)日誌的日誌。

long getExternalStoreFreeSpace ()

確定設備外部存儲上可用空間量的輔助方法。

String getFastbootPath ()

返回正在使用的fastboot二進製文件的路徑。

String getFastbootProductType ()

在快速啟動模式下獲取此設備產品類型的便捷方法。

String getFastbootProductVariant ()

在快速啟動模式下獲取此設備產品類型的便捷方法。

String getFastbootVersion ()

返回所使用的fastboot二進製文件的版本字符串。

IFileEntry getFileEntry (String path)

檢索對設備上遠程文件的引用。

IFileEntry getFileEntry (FileListingService.FileEntry entry)

從非根路徑獲取FileEntry非官方幫助者。

IDevice getIDevice ()

返回對關聯的ddmlib IDevice的引用。

getInstalledPackageNames ()

提取設備上存在的應用程序包名稱。

String getIpAddress ()

獲取設備的IP地址。

KeyguardControllerState getKeyguardState ()

返回一個對像以獲取鍵盤鎖的當前狀態;如果不支持,則返回null。

long getLastExpectedRebootTimeMillis ()

返回自System.currentTimeMillis()返回EPOCH以來,Tradefed API上一次觸發重新引導的時間(以毫秒為單位System.currentTimeMillis()

InputStreamSource getLogcat ()

獲取logcat數據的快照流。

InputStreamSource getLogcat (int maxBytes)

捕獲捕獲的logcat數據的最後maxBytes個快照流。

InputStreamSource getLogcatDump ()

獲取設備當前logcat的轉儲。

InputStreamSource getLogcatSince (long date)

從提供的日期開始獲取捕獲的logcat數據的快照流。

String getMacAddress ()

返回設備的MAC地址,如果無法從設備查詢,則返回null。

int getMaxNumberOfRunningUsersSupported ()

獲取受支持的同時運行用戶的最大數量。

int getMaxNumberOfUsersSupported ()

獲取支持的最大用戶數。

IDeviceStateMonitor getMonitor ()

返回與設備關聯的IDeviceStateMonitor

String getMountPoint (String mountName)

返回安裝點。

ITestDevice.MountPointInfo getMountPointInfo (String mountpoint)

返回與指定的安裝點路徑相對應的MountPointInfo如果該路徑沒有安裝任何內容,或者否則未在/ proc / mounts中顯示為安裝點,則返回null

getMountPointInfo ()

返回設備上/ proc / mounts中信息的解析版本

TestDeviceOptions getOptions ()

獲取設備的測試選項。

long getPartitionFreeSpace (String partition)

確定設備分區上可用空間量的輔助方法。

Integer getPrimaryUserId ()

返回主要用戶ID。

ProcessInfo getProcessByName (String processName)

Helper方法運行“ ps”命令並返回給定進程名稱的USER,PID和NAME。

String getProcessPid (String process)

返回服務的pid;如果出現問題,則返回null。

getProcesses ()

Helper方法運行“ ps”命令並返回所有進程的USER,PID和NAME的列表。

String getProductType ()

獲取此設備產品類型的便捷方法。

String getProductVariant ()

獲取此設備產品變型的便捷方法。

String getProperty (String name)

從設備檢索給定的屬性值。

ITestDevice.RecoveryMode getRecoveryMode ()

獲取用於設備的當前恢復模式。

InputStreamSource getScreenshot (int displayId)

從給定顯示ID的設備中抓取屏幕截圖。

InputStreamSource getScreenshot (String format)

從設備抓取屏幕截圖。

InputStreamSource getScreenshot (String format, boolean rescale)

從設備抓取屏幕截圖。

InputStreamSource getScreenshot ()

從設備抓取屏幕截圖。

String getSerialNumber ()

獲取此設備序列號的便捷方法。

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

返回所請求設置的值。

String getSetting (String namespace, String key)

請參見getSetting(int, String, String)並在系統用戶上執行。

String getSimOperator ()

返回SIM卡操作員;如果設備不可用,則返回null。

String getSimState ()

返回SIM卡狀態;如果設備不可用,則返回null。

getTombstones ()

從設備中獲取並返回邏輯刪除列表。

long getTotalMemory ()

返回總的物理內存大小(以字節為單位),如果發生內部錯誤,則返回-1

getUninstallablePackageNames ()

獲取可以卸載的應用程序包名稱。

boolean getUseFastbootErase ()

獲取是使用fastboot擦除還是fastboot格式擦除設備上的分區。

int getUserFlags (int userId)

查找並返回給定用戶的標誌。

getUserInfos ()

獲取useId到設備上UserInfo的映射。

int getUserSerialNumber (int userId)

返回與userId關聯的序列號(如果找到),在其他情況下為-10000。

IManagedTestDevice.DeviceEventResponse handleAllocationEvent (DeviceEvent event)

處理給定的DeviceEvent

處理DeviceEvent,該事件可能會或可能不會將此設備轉換為新的分配狀態。

boolean hasFeature (String feature)

檢查設備上是否有功能。

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

在設備上安裝Android軟件包。

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

在設備上安裝Android軟件包。

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

在設備上為給定用戶安裝Android軟件包。

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

在設備上為給定用戶安裝Android軟件包。

boolean isAdbRoot ()

boolean isAdbTcp ()
boolean isDeviceEncrypted ()

返回設備是否已加密。

boolean isDirectory (String path)

如果設備上的路徑是目錄,則返回True,否則返回false。

boolean isEnableAdbRoot ()
boolean isEncryptionSupported ()

返回設備是否支持加密。

boolean isExecutable (String fullPath)

如果設備上的文件路徑是可執行文件,則返回True,否則返回false。

boolean isFastbootEnabled ()

如果fastboot可用於該設備,則返回。

boolean isHeadless ()

如果設備無頭(無屏幕),則返回true,否則返回false。

boolean isMultiUserSupported ()

確定是否支持多用戶。

boolean isPackageInstalled (String packageName, String userId)

在設備上查詢給定的程序包名稱和用戶ID,以檢查該用戶當前是否已安裝該設備。

boolean isPackageInstalled (String packageName)

在設備上查詢給定的軟件包名稱,以檢查當前是否已安裝。

boolean isRuntimePermissionSupported ()

檢查設備上的平台是否支持運行時權限授予

boolean isUserRunning (int userId)

檢查給定用戶是否正在運行。

boolean isUserSecondary (int userId)

返回根據其標誌指定的用戶是否是輔助用戶。

boolean isWifiEnabled ()

測試是否啟用了wifi。

listDisplayIds ()

收集“ dumpsys SurfaceFlinger”報告的設備上可用顯示ID的列表。

listUsers ()

獲取設備上的用戶列表。

boolean logBugreport (String dataName, ITestLogger listener)

進行錯誤報告並將其記錄到報告程序的助手方法。

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

在設備的日誌中記錄一條消息。

void nonBlockingReboot ()

發出命令以重新引導設備,並在命令完成後以及adb不再可見設備時返回。

void postAdbRootAction ()

如果設備需要在adb root之後且設備重新聯機之前執行某些特定操作,則重寫。

void postAdbUnrootAction ()

如果設備需要在adb unroot之後且設備重新聯機之前執行某些特定操作,則覆蓋此參數。

void postBootSetup ()

執行說明以配置設備以在每次引導後對其進行測試。

void postInvocationTearDown ()

特定於設備的所需額外清理步驟將在調用完成後執行。

void preInvocationSetup ( IBuildInfo info)

設備特定的必需設置的額外步驟將在調用流程之前在設備上執行。

boolean pullDir (String deviceFilePath, File localDir)

從設備遞歸提取目錄內容。

boolean pullFile (String remoteFilePath, File localFile)

從設備上檢索文件。

File pullFile (String remoteFilePath)

從設備上檢索文件,將其存儲在本地臨時ERROR(/File) ,然後返回該File

String pullFileContents (String remoteFilePath)

從設備上檢索文件,然後返回內容。

File pullFileFromExternal (String remoteFilePath)

一種從設備的外部存儲中檢索文件,將其存儲在本地臨時ERROR(/File)中並返回對該File的引用的便捷方法。

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

將目錄內容遞歸推送到設備,同時排除一些已過濾的目錄。

boolean pushDir (File localFileDir, String deviceFilePath)

遞歸將目錄內容推送到設備。

boolean pushFile (File localFile, String remoteFilePath)

將文件推送到設備

boolean pushString (String contents, String remoteFilePath)

將從字符串創建的文件推送到設備

void reboot ()

將設備重新引導到adb模式。

void rebootIntoBootloader ()

將設備重新引導到引導加載程序模式。

void rebootIntoRecovery ()

將設備重新引導到adb恢復模式。

void rebootUntilOnline ()

一個reboot()的替代方法,它僅在設備聯機之前才阻塞,即對adb可見。

void recoverDevice ()

嘗試恢復設備通信。

void remountSystemWritable ()

使設備上的系統分區可寫。

boolean removeAdmin (String componentName, int userId)

刪除給定用戶中的給定設備管理員,如果成功則返回true ,否則返回false

void removeOwners ()

盡最大努力刪除所有現有的設備配置文件所有者。

boolean removeUser (int userId)

從設備中刪除給定的用戶。

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

使用一個或多個作為參數傳遞的偵聽器執行ERROR(/#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection))便捷方法。

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

運行儀器測試,並提供設備恢復。

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

ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, ITestLifeCycleReceiver...)但為給定用戶運行測試。

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

ERROR(ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)/com.android.tradefed.device.ITestDevice#runInstrumentationTests(com.android.ddmlib.testrunner.IRemoteAndroidTestRunner,Collection) ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection))給定的用戶。

void setDate (Date date)

在設備上設置日期

注意:在設備上設置日期需要root

boolean setDeviceOwner (String componentName, int userId)

將設備管理員組件設置為給定用戶中的設備所有者。

void setDeviceState ( TestDeviceState deviceState)

更新設備的狀態。

void setEmulatorOutputStream ( SizeLimitedOutputStream output)

對於模擬器,將SizeLimitedOutputStream設置為記錄輸出

void setEmulatorProcess (Process p)

當此設備是仿真器時,設置Process

void setFastbootEnabled (boolean fastbootEnabled)

設置設備的fastboot選項。

void setFastbootPath (String fastbootPath)

將路徑設置為應使用的fastboot二進製文件。

void setIDevice (IDevice newDevice)

更新與此ITestDevice關聯的IDevice。

void setOptions ( TestDeviceOptions options)

設置設備的TestDeviceOptions

boolean setProperty (String propKey, String propValue)

在設備上設置給定的屬性值。

void setRecovery ( IDeviceRecovery recovery)

設置要用於此設備的IDeviceRecovery

void setRecoveryMode ( ITestDevice.RecoveryMode mode)

設置要用於設備的當前恢復模式。

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

請參見setSetting(int, String, String, String)並在系統用戶上執行。

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

將設置值添加到給定用戶的名稱空間。

void setUseFastbootErase (boolean useFastbootErase)

設置是使用fastboot擦除還是fastboot格式擦除設備上的分區。

void startLogcat ()

開始在後台捕獲設備的logcat輸出。

boolean startUser (int userId)

如果當前已停止,則在後台啟動給定用戶。

boolean startUser (int userId, boolean waitFlag)

如果當前已停止,則在後台啟動給定用戶。

void stopEmulatorOutput ()

關閉並刪除仿真器輸出。

void stopLogcat ()

停止捕獲設備的logcat輸出,並丟棄當前保存的logcat數據。

boolean stopUser (int userId)

停止給定的用戶。

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

停止給定的用戶。

String switchToAdbTcp ()

將設備切換到adb-over-tcp模式。

boolean switchToAdbUsb ()

通過USB模式將設備切換到adb。

boolean switchUser (int userId)

切換到另一個具有默認超時的userId。

boolean switchUser (int userId, long timeout)

使用提供的超時作為截止日期切換到另一個userId。

boolean syncFiles (File localFileDir, String deviceFilePath)

將本地文件目錄的內容增量同步到設備。

Bugreport takeBugreport ()

進行一個錯誤報告,並將其返回到Bugreport像中以進行處理。

boolean unencryptDevice ()

解密設備。

String uninstallPackage (String packageName)

從設備上卸載Android程序包。

boolean unlockDevice ()

如果設備處於加密狀態,則解鎖設備。

boolean waitForBootComplete (long timeOut)

阻塞直到設置設備的啟動完成標誌。

void waitForDeviceAvailable ()

等待設備響應並可以進行測試。

void waitForDeviceAvailable (long waitTime)

等待設備響應並可以進行測試。

boolean waitForDeviceInRecovery (long waitTime)

阻止設備處於“ adb恢復”狀態(請注意,這與IDeviceRecovery不同)。

boolean waitForDeviceNotAvailable (long waitTime)

該設備的塊不可用,即adb丟失

void waitForDeviceOnline ()

阻塞,直到通過adb看到設備為止。

void waitForDeviceOnline (long waitTime)

阻塞,直到通過adb看到設備為止。

boolean waitForDeviceShell (long waitTime)

等待設備響應基本的adb shell命令。

受保護的方法

void checkApiLevelAgainst (String feature, int strictMinLevel)
NativeDevice.RebootDeviceAction createRebootDeviceAction (String into)

創建一個RebootDeviceAction ,以在執行重啟操作時使用。

void doAdbReboot (String into)

執行adb重新啟動。

void ensureRuntimePermissionSupported ()

如果不支持運行時權限,則拋出異常的輔助方法

InputStreamSource getBugreportInternal ()
File getBugreportzInternal ()

用於將bugreportz zip文件獲取為ERROR(/File)內部Helper方法。

IRunUtil getRunUtil ()

獲取要使用的RunUtil實例。

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

默認情況下,從ddmlib緩存中獲取設備屬性,然後根據設備是否處於Fastboot來回退至“ adb shell getprop”或“ fastboot getvar”。

boolean isNewer (File localFile, IFileEntry entry)

如果本地文件比遠程文件新,則返回true

boolean performDeviceAction (String actionDescription, com.android.tradefed.device.NativeDevice.DeviceAction action, int retryAttempts)

在此設備上執行操作。

void postAdbReboot ()

重新啟動後可以採取的可能的額外操作。

void prePostBootSetup ()

允許每種設備類型(AndroidNativeDevice,TestDevice)針對特定的啟動後設置覆蓋此方法。

void setClock (Clock clock)

設置要使用的Clock實例。

void setLogStartDelay (int delay)

設置開始在線設備捕獲日誌之前要等待的時間(以毫秒為單位)。

void waitForDeviceNotAvailable (String operationDesc, long time)

常數

INVALID_USER_ID

public static final int INVALID_USER_ID

對於任何無效/未找到的用戶ID返回的值:UserHandle定義了-10000值

常數:-10000(0xffffd8f0)

MAX_HOST_DEVICE_TIME_OFFSET

protected static final long MAX_HOST_DEVICE_TIME_OFFSET

常數值:5000(0x0000000000001388)

MAX_RETRY_ATTEMPTS

protected static final int MAX_RETRY_ATTEMPTS

默認的命令重試嘗試次數

常數值:2(0x00000002)

領域

m選項

protected TestDeviceOptions mOptions

mStateMonitor

protected final IDeviceStateMonitor mStateMonitor

公共建設者

本機設備

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

創建一個TestDevice

參量
device IDevice :關聯的IDevice

stateMonitor IDeviceStateMonitor :要使用的IDeviceStateMonitor機制

allocationMonitor IDeviceMonitorIDeviceMonitor通知分配狀態更改。可以為空

公開方法

checkApiLevelAgainstNextRelease

public boolean checkApiLevelAgainstNextRelease (int strictMinLevel)

在最低支持級別下,檢查當前是否支持某個功能。在提高API級別之前,此方法會考慮尚未發布的功能。

參量
strictMinLevel int :支持該功能的嚴格的最小可能級別。

退貨
boolean 如果支持級別,則為True。否則為假。

投擲
DeviceNotAvailableException

checkConnectivity

public boolean checkConnectivity ()

檢查設備是否具有網絡連接。

退貨
boolean 如果設備的網絡連接正常,則為true否則為false

投擲
DeviceNotAvailableException

clearErrorDialogs

public boolean clearErrorDialogs ()

嘗試關閉設備界面上當前顯示的所有錯誤對話框。

退貨
boolean 如果不存在對話框或成功清除對話框,則為true 。否則為false

投擲
DeviceNotAvailableException

clearLastConnectedWifiNetwork

public void clearLastConnectedWifiNetwork ()

清除最後連接的wifi網絡。在開始新的調用時應調用此函數,以避免設備重啟後連接到先前測試中使用的wifi網絡。

clearLogcat

public void clearLogcat ()

刪除任何累積的logcat數據。

當您要確保ITestDevice#getLogcat()僅返回在特定時間點之後生成的日誌數據(例如在刷新新的設備版本後等)時,這很有用。

connectToWifiNetwork

public boolean connectToWifiNetwork (String wifiSsid, 
                String wifiPsk)

連接到wifi網絡。

打開wifi並阻止,直到成功連接到指定的wifi網絡為止。建立連接後,實例將在每次重新啟動後嘗試恢復連接,直到ITestDevice#disconnectFromWifi()ITestDevice#clearLastConnectedWifiNetwork()

參量
wifiSsid String :要連接的wifi ssid

wifiPsk String :PSK密碼,如果未加密,則為null

退貨
boolean 如果成功連接到wifi網絡,則為true 。否則為false

投擲
DeviceNotAvailableException

connectToWifiNetwork

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

連接到wifi網絡。

打開wifi並阻止,直到成功連接到指定的wifi網絡為止。建立連接後,實例將在每次重新啟動後嘗試恢復連接,直到ITestDevice#disconnectFromWifi()ITestDevice#clearLastConnectedWifiNetwork()

參量
wifiSsid String :要連接的wifi ssid

wifiPsk String :PSK密碼,如果未加密,則為null

scanSsid boolean :是否掃描此網絡的隱藏SSID。

退貨
boolean 如果成功連接到wifi網絡,則為true 。否則為false

投擲
DeviceNotAvailableException

需要時連接到Wifi網絡

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

connectToWifiNetwork(String, String)變體,僅在設備當前沒有網絡連接時才連接。

參量
scanSsid boolean :是否掃描此網絡的隱藏SSID

退貨
boolean 如果成功連接到wifi網絡,則為true 。否則為false

投擲
DeviceNotAvailableException

需要時連接到Wifi網絡

public boolean connectToWifiNetworkIfNeeded (String wifiSsid, 
                String wifiPsk)

connectToWifiNetwork(String, String)變體,僅在設備當前沒有網絡連接時才連接。

退貨
boolean 如果成功連接到wifi網絡,則為true 。否則為false

投擲
DeviceNotAvailableException

創建用戶

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

創建具有給定名稱和提供的標誌的用戶

參量
name String :要在設備上創建的用戶的String

guest boolean :在創建過程中啟用用戶標誌--guest

ephemeral boolean :在創建過程中啟用用戶標誌--ephemeral

退貨
int 創建的用戶的ID

投擲
DeviceNotAvailableException

創建用戶

public int createUser (String name)

創建一個具有給定名稱和默認標誌0的用戶。

參量
name String :要在設備上創建的用戶的String

退貨
int 創建的用戶ID的整數

投擲
DeviceNotAvailableException

createUserNoThrow

public int createUserNoThrow (String name)

創建一個具有給定名稱和默認標誌0的用戶。

參量
name String :要在設備上創建的用戶的String

退貨
int 創建的用戶ID的整數,或-1表示錯誤。

投擲
DeviceNotAvailableException

刪除文件

public void deleteFile (String deviceFilePath)

刪除設備上文件或目錄的幫助方法。

參量
deviceFilePath String :設備上文件的絕對路徑。

投擲
DeviceNotAvailableException

disableAdbRoot

public boolean disableAdbRoot ()

關閉adb根目錄。

禁用adb root可能會導致設備與adb斷開連接。該方法將阻塞,直到設備可用。

退貨
boolean 如果成功,則為true

投擲
DeviceNotAvailableException

disableKeyguard

public void disableKeyguard ()

嘗試禁用鍵盤鎖。

首先等待輸入分發準備就緒,這大約在設備報告BOOT_COMPLETE的同時發生,這顯然是異步的,因為當前框架實現有時會出現競爭狀況。然後發送命令以關閉鍵盤鎖(僅適用於不安全的鍵盤鎖)

投擲
DeviceNotAvailableException

disableNetworkMonitor

public boolean disableNetworkMonitor ()

在設備上禁用網絡監視。

退貨
boolean 如果成功禁用監視,則為true 。如果失敗,則返回false

投擲
DeviceNotAvailableException

從Wifi斷開

public boolean disconnectFromWifi ()

斷開與wifi網絡的連接。

從已知網絡列表中刪除所有網絡並禁用wifi。

退貨
boolean 如果成功從wifi網絡斷開連接,則為true 。如果斷開連接失敗,則返回false

投擲
DeviceNotAvailableException

didFileExist

public boolean doesFileExist (String deviceFilePath)

確定設備上文件是否存在的輔助方法。

參量
deviceFilePath String :要檢查的設備上文件的絕對路徑

退貨
boolean 如果文件存在,則為true ,否則為false

投擲
DeviceNotAvailableException

dumpHeap

public File dumpHeap (String process, 
                String devicePath)

嘗試從system_server中轉儲堆。清理轉儲文件是呼叫者的責任。

參量
process String :要在其上進行轉儲的設備進程的名稱。

devicePath String :設備上放置轉儲的路徑。這必須是權限允許的位置。

退貨
File 包含報告的ERROR(/File) 。如果失敗,則為Null。

投擲
DeviceNotAvailableException

enableAdbRoot

public boolean enableAdbRoot ()

打開adb根目錄。如果“ enable-root”設置為“ false”,將記錄一條消息並返回而不啟用root。

啟用adb root可能會導致設備與adb斷開連接。該方法將阻塞,直到設備可用。

退貨
boolean 如果成功,則為true

投擲
DeviceNotAvailableException

enableNetworkMonitor

public boolean enableNetworkMonitor ()

在設備上啟用網絡監視。

退貨
boolean 如果成功啟用監視,則為true 。如果失敗,則返回false

投擲
DeviceNotAvailableException

cryptoDevice

public boolean encryptDevice (boolean inplace)

加密設備。

可以對設備進行加密或就位進行加密。就地加密不會擦除設備上的任何數據,但通常比擦除要長幾個數量級。

如果該設備尚未加密,則此方法將重新啟動設備,並在設備聯機之前將其阻止。此外,重啟後它不會解密設備。因此,當此方法返回時,設備可能未完全啟動和/或未準備好進行測試。

參量
inplace boolean :如果加密過程應該就位並且不應擦除設備。

退貨
boolean 如果成功,則為true

投擲
DeviceNotAvailableException

executeAdbCommand

public String executeAdbCommand (String... cmdArgs)

將adb命令作為系統命令執行的Helper方法。

應盡可能使用executeShellCommand(String)代替,因為該方法可提供更好的故障檢測和性能。

參量
cmdArgs String :adb命令和要運行的參數

退貨
String 命令的標準輸出。如果命令執行失敗,則返回null

投擲
DeviceNotAvailableException

executeFastbootCommand

public CommandResult executeFastbootCommand (String... cmdArgs)

幫助程序方法,將fastboot命令作為系統命令執行,默認超時為2分鐘。

預期在設備已經處於快速啟動模式時使用。

參量
cmdArgs String :fastboot命令和要運行的參數

退貨
CommandResult 包含命令輸出的CommandResult

投擲
DeviceNotAvailableException

executeFastbootCommand

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

將fastboot命令作為系統命令執行的Helper方法。

預期在設備已經處於快速啟動模式時使用。

參量
timeout long :命令到期前的時間(以毫秒為單位)

cmdArgs String :fastboot命令和要運行的參數

退貨
CommandResult 包含命令輸出的CommandResult

投擲
DeviceNotAvailableException

executeLongFastbootCommand

public CommandResult executeLongFastbootCommand (String... cmdArgs)

將長時間運行的fastboot命令作為系統命令執行的Helper方法。

executeFastbootCommand(String)相同,除了使用更長的超時時間。

參量
cmdArgs String :fastboot命令和要運行的參數

退貨
CommandResult 包含命令輸出的CommandResult

投擲
DeviceNotAvailableException

executeShellCommand

public String executeShellCommand (String command)

執行adb shell命令並以String返回輸出的Helper方法。

參量
command String :要運行的adb shell命令

退貨
String 外殼輸出

投擲
DeviceNotAvailableException

executeShellCommand

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

執行adb shell命令,並使用更多參數來控制命令行為。

參量
command String :要運行的adb shell命令

receiver IShellOutputReceiver :將Shell輸出IShellOutputReceiver到的IShellOutputReceiver

maxTimeToOutputShellResponse long :允許命令不輸出任何響應的最longtimeUnit指定的timeUnit

timeUnit TimeUnitmaxTimeToOutputShellResponse單位

retryAttempts int :命令由於異常而失敗的最大重試次數。如果執行retryAttempts失敗,將引發retryAttempts

投擲
DeviceNotAvailableException

executeShellCommand

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

執行adb shell命令,並使用更多參數來控制命令行為。

參量
command String :要運行的adb shell命令

receiver IShellOutputReceiver :將Shell輸出IShellOutputReceiver到的IShellOutputReceiver

maxTimeoutForCommand long :命令完成的最大超時; timeUnit指定的timeUnit

maxTimeToOutputShellResponse long :允許命令不輸出任何響應的最longtimeUnit指定的timeUnit

timeUnit TimeUnitmaxTimeToOutputShellResponse單位

retryAttempts int :命令由於異常而失敗的最大重試次數。如果執行retryAttempts失敗,將引發retryAttempts

投擲
DeviceNotAvailableException

executeShellCommand

public void executeShellCommand (String command, 
                IShellOutputReceiver receiver)

執行給定的adb shell命令,如果命令失敗,則重試多次。

一種帶有默認值的executeShellCommand(String, com.android.ddmlib.IShellOutputReceiver, long, TimeUnit, int)的簡單形式。

參量
command String :要運行的adb shell命令

receiver IShellOutputReceiver :將Shell輸出IShellOutputReceiver到的IShellOutputReceiver

投擲
DeviceNotAvailableException

executeShellV2Command

public CommandResult executeShellV2Command (String cmd)

Helper方法,該方法執行adb shell命令,並將結果作為CommandResult返回,並正確填充命令狀態輸出stdout和stderr。

參量
cmd String :應運行的命令。

退貨
CommandResult CommandResult的結果。

投擲
DeviceNotAvailableException

executeShellV2Command

public CommandResult executeShellV2Command (String cmd, 
                OutputStream pipeToOutput)

Helper方法,該方法執行adb shell命令,並將結果作為CommandResult返回,並正確填充命令狀態輸出stdout和stderr。

參量
cmd String :應運行的命令。

pipeToOutput OutputStreamERROR(/OutputStream)將在其中重定向標準輸出。

退貨
CommandResult CommandResult的結果。

投擲
DeviceNotAvailableException

executeShellV2Command

public CommandResult executeShellV2Command (String cmd, 
                File pipeAsInput)

Helper方法,該方法執行adb shell命令,並將結果作為CommandResult返回,並正確填充命令狀態輸出stdout和stderr。

參量
cmd String :應運行的命令。

pipeAsInput FileERROR(/File) ,將通過管道將其作為命令的輸入。

退貨
CommandResult CommandResult的結果。

投擲
DeviceNotAvailableException

executeShellV2Command

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

執行adb shell命令,並使用更多參數來控制命令行為。

參量
cmd String :要運行的adb shell命令

maxTimeoutForCommand long :命令完成的最大超時; timeUnit指定的timeUnit

timeUnit TimeUnitmaxTimeToOutputShellResponse單位

retryAttempts int :命令由於異常而失敗的最大重試次數。如果執行retryAttempts失敗,將引發retryAttempts

退貨
CommandResult

投擲
DeviceNotAvailableException

executeShellV2Command

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

執行adb shell命令,並使用更多參數來控制命令行為。

參量
cmd String :要運行的adb shell命令

maxTimeoutForCommand long :命令完成的最大超時; timeUnit指定的timeUnit

timeUnit TimeUnitmaxTimeToOutputShellResponse單位

退貨
CommandResult

投擲
DeviceNotAvailableException

executeShellV2Command

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

執行adb shell命令,並使用更多參數來控制命令行為。

參量
cmd String :要運行的adb shell命令

pipeAsInput FileERROR(/File) ,將通過管道將其作為命令的輸入。

pipeToOutput OutputStreamERROR(/OutputStream)將在其中重定向標準輸出。

maxTimeoutForCommand long :命令完成的最大超時; timeUnit指定的timeUnit

timeUnit TimeUnitmaxTimeToOutputShellResponse單位

retryAttempts int :命令由於異常而失敗的最大重試次數。如果執行retryAttempts沒有成功,則將引發retryAttempts

退貨
CommandResult

投擲
DeviceNotAvailableException

fastbootWipePartition

public CommandResult fastbootWipePartition (String partition)

擦除設備分區的輔助方法。

如果getUseFastbootErase()true ,則快速啟動擦除將用於擦除分區。然後,設備必須在下次引導時創建文件系統。否則,將使用快速啟動格式,該格式將在設備上創建新的文件系統。

預期在設備已經處於快速啟動模式時使用。

參量
partition String :要擦除的分區

退貨
CommandResult 包含命令輸出的CommandResult

投擲
DeviceNotAvailableException

getActiveApexes

public  getActiveApexes ()

獲取有關在設備上激活的APEX的信息。

退貨
設備上當前激活的ApexInfo ERROR(/Set)

投擲
DeviceNotAvailableException

getAllSettings

public  getAllSettings (String namespace)

返回請求的名稱空間的鍵值對。

參量
namespace String :必須是{“ system”,“ secure”,“ global”}中的一個

退貨
鍵值對的映射。如果不支持名稱空間,則為Null。

投擲
DeviceNotAvailableException

getAllocationState

public DeviceAllocationState getAllocationState ()

返回設備的當前分配狀態

退貨
DeviceAllocationState

getAndroidId

public String getAndroidId (int userId)

查找並返回與userId關聯的android-id,如果未找到,則返回null。

參量
userId int

退貨
String

投擲
DeviceNotAvailableException

getAndroidIds

public  getAndroidIds ()

創建一個與用戶ID匹配的android ID映射。沒有保證每個用戶ID都會在此函數中找到關聯的Android ID,因此某些用戶ID可能與null匹配。

退貨
找到與用戶ID匹配的android ID映射。

投擲
DeviceNotAvailableException

getApiLevel

public int getApiLevel ()

獲取設備API級別。默認為UNKNOWN_API_LEVEL

退貨
int 一個整數,指示設備的API級別

投擲
DeviceNotAvailableException

getAppPackageInfo

public PackageInfo getAppPackageInfo (String packageName)

獲取有關設備上安裝的軟件包的信息。

參量
packageName String

退貨
PackageInfo PackageInfo如果無法檢索信息,則返回null

投擲
DeviceNotAvailableException

getBasebandVersion

public String getBasebandVersion ()

獲取此設備的基帶(無線電)版本的便捷方法。獲取無線電版本是特定於設備的,因此它可能不會為所有設備返回正確的信息。此方法依賴gsm.version.baseband屬性返回正確的版本信息。對於某些CDMA設備,這是不准確的,並且此處返回的版本可能與fastboot報告的版本不匹配,並且可能不會返回CDMA無線電的版本。 TL; DR如果gsm.version.baseband屬性與fastboot getvar version-baseband返回的版本相同,則此方法僅報告準確的版本。

退貨
String String基帶版本;如果無法確定,則為null (設備沒有廣播或無法讀取版本字符串)

投擲
DeviceNotAvailableException

getBattery

public Integer getBattery ()

返回設備的當前電池電量;如果電池電量不可用,則返回Null。

退貨
Integer

getBootloaderVersion

public String getBootloaderVersion ()

獲取此設備的引導程序版本的便捷方法。

將嘗試從設備的當前狀態檢索引導加載程序版本。 (即,如果設備處於快速啟動模式,它將嘗試從快速啟動中檢索版本)

退貨
String String引導加載程序版本;如果找不到,則返回null

投擲
DeviceNotAvailableException

getBugreport

public InputStreamSource getBugreport ()

從設備檢索錯誤報告。

The implementation of this is guaranteed to continue to work on a device without an sdcard (or where the sdcard is not yet mounted).

Returns
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

Returns
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

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

Throws
DeviceNotAvailableException

getBuildFlavor

public String getBuildFlavor ()

Retrieve the build flavor for the device.

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

Throws
DeviceNotAvailableException

getBuildId

public String getBuildId ()

Retrieve the build the device is currently running.

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

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

Returns
String The signing key if found, null otherwise.

Throws
DeviceNotAvailableException

getChildren

public String[] getChildren (String path)

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

Parameters
path String : is the path on the device where to do the search

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

Throws
DeviceNotAvailableException

getCurrentUser

public int getCurrentUser ()

Return the id of the current running user.

Returns
int

Throws
DeviceNotAvailableException

getDeviceClass

public String getDeviceClass ()

Get the device class.

Returns
String the String device class.

getDeviceDate

public long getDeviceDate ()

Return the date of the device in millisecond since epoch.

Returns
long the date of the device in epoch format.

Throws
DeviceNotAvailableException

getDeviceDescriptor

public DeviceDescriptor getDeviceDescriptor ()

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

Returns
DeviceDescriptor

getDeviceState

public TestDeviceState getDeviceState ()

Get the device's state.

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

Parameters
date Date

Returns
long the difference in milliseconds

Throws
DeviceNotAvailableException

getEmulatorOutput

public InputStreamSource getEmulatorOutput ()

Get the stream of emulator stdout and stderr

Returns
InputStreamSource emulator output

getEmulatorProcess

public Process getEmulatorProcess ()

Return the Process corresponding to this emulator.

Returns
Process the Process or null

getExecuteShellCommandLog

public final File getExecuteShellCommandLog ()

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

Returns
File

getExternalStoreFreeSpace

public long getExternalStoreFreeSpace ()

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

Returns
long the amount of free space in KB

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

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

Returns
String the String product type name or null if it cannot be determined

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

Returns
String the String product type name or null if it cannot be determined

Throws
DeviceNotAvailableException

getFastbootVersion

public String getFastbootVersion ()

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

Returns
String

getFileEntry

public IFileEntry getFileEntry (String path)

Retrieve a reference to a remote file on device.

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

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

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

Parameters
entry FileListingService.FileEntry : a FileEntry not necessarily root as Ddmlib requires.

Returns
IFileEntry a FileEntryWrapper representing the FileEntry.

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

Returns
IDevice the IDevice

getInstalledPackageNames

public  getInstalledPackageNames ()

Fetch the application package names present on the device.

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

Throws
DeviceNotAvailableException

getIpAddress

public String getIpAddress ()

Gets the device's IP address.

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

Throws
DeviceNotAvailableException

getKeyguardState

public KeyguardControllerState getKeyguardState ()

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

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

Throws
DeviceNotAvailableException

getLastExpectedRebootTimeMillis

public long getLastExpectedRebootTimeMillis ()

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

Returns
long

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

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

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

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

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

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

    Returns
    InputStreamSource

    getMacAddress

    public String getMacAddress ()

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

    Returns
    String

    getMaxNumberOfRunningUsersSupported

    public int getMaxNumberOfRunningUsersSupported ()

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

    Returns
    int an integer indicating the number of simultaneously running users

    Throws
    DeviceNotAvailableException

    getMaxNumberOfUsersSupported

    public int getMaxNumberOfUsersSupported ()

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

    Returns
    int an integer indicating the number of supported users

    Throws
    DeviceNotAvailableException

    getMonitor

    public IDeviceStateMonitor getMonitor ()

    Return the IDeviceStateMonitor associated with device.

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

    Parameters
    mountName String : the name of the mount point

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

    Parameters
    mountpoint String

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

    Throws
    DeviceNotAvailableException

    getMountPointInfo

    public  getMountPointInfo ()

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

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

    Throws
    DeviceNotAvailableException

    getOptions

    public TestDeviceOptions getOptions ()

    Fetch the test options for the device.

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

    Parameters
    partition String

    Returns
    long the amount of free space in KB

    Throws
    DeviceNotAvailableException

    getPrimaryUserId

    public Integer getPrimaryUserId ()

    Returns the primary user id.

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

    Throws
    DeviceNotAvailableException

    getProcessByName

    public ProcessInfo getProcessByName (String processName)

    Helper method runs the "ps" command and returns USER, PID and NAME of the given process name.

    Parameters
    processName String

    Returns
    ProcessInfo ProcessInfo of given processName

    Throws
    DeviceNotAvailableException

    getProcessPid

    public String getProcessPid (String process)

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

    Parameters
    process String

    Returns
    String

    Throws
    DeviceNotAvailableException

    getProcesses

    public  getProcesses ()

    Helper method runs the "ps" command and returns list of USER, PID and NAME of all the processes.

    Returns
    List of ProcessInfo objects

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

    Returns
    String the String product type name. Will not be null

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

    Returns
    String the String product variant name or null if it cannot be determined

    Throws
    DeviceNotAvailableException

    getProperty

    public String getProperty (String name)

    Retrieve the given property value from the device.

    Parameters
    name String : the property name

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

    Throws
    DeviceNotAvailableException

    getRecoveryMode

    public ITestDevice.RecoveryMode getRecoveryMode ()

    Get the current recovery mode used for the device.

    Returns
    ITestDevice.RecoveryMode the current recovery mode used for the device.

    getScreenshot

    public InputStreamSource getScreenshot (int displayId)

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

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

    Parameters
    displayId int : the display id of the screen to get screenshot from.

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

    Throws
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot (String format)

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

    Parameters
    format String : supported PNG, JPEG

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

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

    Parameters
    format String : supported PNG, JPEG

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

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

    Throws
    DeviceNotAvailableException

    getScreenshot

    public InputStreamSource getScreenshot ()

    Grabs a screenshot from the device.

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

    Throws
    DeviceNotAvailableException

    getSerialNumber

    public String getSerialNumber ()

    Convenience method to get serial number of this device.

    Returns
    String the String serial number

    getSetting

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

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

    Parameters
    userId int

    namespace String

    key String

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

    Throws
    DeviceNotAvailableException

    getSetting

    public String getSetting (String namespace, 
                    String key)

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

    Parameters
    namespace String

    key String

    Returns
    String

    Throws
    DeviceNotAvailableException

    getSimOperator

    public String getSimOperator ()

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

    Returns
    String

    getSimState

    public String getSimState ()

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

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

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

    Throws
    DeviceNotAvailableException

    getTotalMemory

    public long getTotalMemory ()

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

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

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

    Throws
    DeviceNotAvailableException

    getUseFastbootErase

    public boolean getUseFastbootErase ()

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

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

    Parameters
    userId int

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

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

    Returns
    the list of UserInfo objects.

    Throws
    DeviceNotAvailableException

    getUserSerialNumber

    public int getUserSerialNumber (int userId)

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

    Parameters
    userId int

    Returns
    int

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

    Parameters
    event DeviceEvent

    Returns
    IManagedTestDevice.DeviceEventResponse

    hasFeature

    public boolean hasFeature (String feature)

    Check if a feature is available on a device.

    Parameters
    feature String : which format should be "feature: ".

    Returns
    boolean True if feature is found, false otherwise.

    Throws
    DeviceNotAvailableException

    installPackage

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

    Install an Android package on device.

    Parameters
    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 install --help' for available options.

    Returns
    String a String with an error code, or null if success.

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

    Parameters
    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 install --help' for available options.

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    installPackageForUser

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

    Install an Android package on device for a given user.

    Parameters
    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 install --help' for available options.

    Returns
    String a String with an error code, or null if success.

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

    Parameters
    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 install --help' for available options.

    Returns
    String a String with an error code, or null if success.

    Throws
    DeviceNotAvailableException

    isAdbRoot

    public boolean isAdbRoot ()

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isAdbTcp

    public boolean isAdbTcp ()

    Returns
    boolean

    isDeviceEncrypted

    public boolean isDeviceEncrypted ()

    Returns if the device is encrypted.

    Returns
    boolean true if the device is encrypted.

    Throws
    DeviceNotAvailableException

    isDirectory

    public boolean isDirectory (String path)

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

    Parameters
    path String

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isEnableAdbRoot

    public boolean isEnableAdbRoot ()

    Returns
    boolean true if adb root should be enabled on device

    isEncryptionSupported

    public boolean isEncryptionSupported ()

    Returns if encryption is supported on the device.

    Returns
    boolean true if the device supports encryption.

    Throws
    DeviceNotAvailableException

    isExecutable

    public boolean isExecutable (String fullPath)

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

    Parameters
    fullPath String

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isFastbootEnabled

    public boolean isFastbootEnabled ()

    Return if fastboot is available for the device.

    Returns
    boolean

    isHeadless

    public boolean isHeadless ()

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

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    isMultiUserSupported

    public boolean isMultiUserSupported ()

    Determines if multi user is supported.

    Returns
    boolean true if multi user is supported, false otherwise

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

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

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

    Throws
    DeviceNotAvailableException

    isPackageInstalled

    public boolean isPackageInstalled (String packageName)

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

    Parameters
    packageName String

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

    Throws
    DeviceNotAvailableException

    isRuntimePermissionSupported

    public boolean isRuntimePermissionSupported ()

    Check whether platform on device supports runtime permission granting

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

    Throws
    DeviceNotAvailableException

    isUserRunning

    public boolean isUserRunning (int userId)

    Check if a given user is running.

    Parameters
    userId int

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

    Throws
    DeviceNotAvailableException

    isUserSecondary

    public boolean isUserSecondary (int userId)

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

    Parameters
    userId int

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

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

    Returns
    boolean true if wifi is enabled. false if disabled

    Throws
    DeviceNotAvailableException

    listDisplayIds

    public  listDisplayIds ()

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

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

    Throws
    DeviceNotAvailableException

    listUsers

    public  listUsers ()

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

    Returns
    the list of user ids.

    Throws
    DeviceNotAvailableException

    logBugreport

    public boolean logBugreport (String dataName, 
                    ITestLogger listener)

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

    Parameters
    dataName String : name under which the bugreport will be reported.

    listener ITestLogger : an ITestLogger to log the bugreport.

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

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

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

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

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

    Throws
    DeviceNotAvailableException

    postInvocationTearDown

    public void postInvocationTearDown ()

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

    preInvocationSetup

    public void preInvocationSetup ( IBuildInfo info)

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

    Parameters
    info IBuildInfo

    Throws
    DeviceNotAvailableException
    TargetSetupError

    pullDir

    public boolean pullDir (String deviceFilePath, 
                    File localDir)

    Recursively pull directory contents from device.

    Parameters
    deviceFilePath String : the absolute file path of the remote source

    localDir File : the local directory to pull files into

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

    Throws
    DeviceNotAvailableException

    pullFile

    public boolean pullFile (String remoteFilePath, 
                    File localFile)

    Retrieves a file off device.

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

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

    Throws
    DeviceNotAvailableException

    pullFile

    public File pullFile (String remoteFilePath)

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

    Parameters
    remoteFilePath String : the absolute path to file on device.

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

    Throws
    DeviceNotAvailableException

    pullFileContents

    public String pullFileContents (String remoteFilePath)

    Retrieves a file off device, and returns the contents.

    Parameters
    remoteFilePath String : the absolute path to file on device.

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

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

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

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

    Throws
    DeviceNotAvailableException

    pushDir

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

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

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

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

    Throws
    DeviceNotAvailableException

    pushDir

    public boolean pushDir (File localFileDir, 
                    String deviceFilePath)

    Recursively push directory contents to device.

    Parameters
    localFileDir File : the local directory to push

    deviceFilePath String : the absolute file path of the remote destination

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

    Throws
    DeviceNotAvailableException

    pushFile

    public boolean pushFile (File localFile, 
                    String remoteFilePath)

    Push a file to device

    Parameters
    localFile File : the local file to push

    remoteFilePath String : the remote destination absolute file path

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

    Throws
    DeviceNotAvailableException

    pushString

    public boolean pushString (String contents, 
                    String remoteFilePath)

    Push file created from a string to device

    Parameters
    contents String : the contents of the file to push

    remoteFilePath String : the remote destination absolute file path

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

    Throws
    DeviceNotAvailableException

    reboot

    public void reboot ()

    Reboots the device into adb mode.

    Blocks until device becomes available.

    Throws
    DeviceNotAvailableException

    rebootIntoBootloader

    public void rebootIntoBootloader ()

    Reboots the device into bootloader mode.

    Blocks until device is in bootloader mode.

    Throws
    DeviceNotAvailableException

    rebootIntoRecovery

    public void rebootIntoRecovery ()

    Reboots the device into adb recovery mode.

    Blocks until device enters recovery

    Throws
    DeviceNotAvailableException

    rebootUntilOnline

    public void rebootUntilOnline ()

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

    Throws
    DeviceNotAvailableException

    recoverDevice

    public void recoverDevice ()

    Attempts to recover device communication.

    Throws
    DeviceNotAvailableException if device is not longer available

    remountSystemWritable

    public void remountSystemWritable ()

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

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

    Parameters
    componentName String : of device admin to be removed.

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

    Returns
    boolean True if it is successful, false otherwise.

    Throws
    DeviceNotAvailableException

    removeOwners

    public void removeOwners ()

    Remove all existing device profile owners with the best effort.

    Throws
    DeviceNotAvailableException

    removeUser

    public boolean removeUser (int userId)

    Remove a given user from the device.

    Parameters
    userId int : of the user to remove

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

    Throws
    DeviceNotAvailableException

    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.

    Parameters
    runner IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests

    listeners ITestLifeCycleReceiver : the test result listener(s)

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

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

    Parameters
    runner IRemoteAndroidTestRunner : the IRemoteAndroidTestRunner which runs the tests

    listeners : the test result listeners

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

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

    Parameters
    runner IRemoteAndroidTestRunner

    userId int

    listeners ITestLifeCycleReceiver

    Returns
    boolean

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

    Parameters
    runner IRemoteAndroidTestRunner

    userId int

    listeners

    Returns
    boolean

    Throws
    DeviceNotAvailableException

    setDate

    public void setDate (Date date)

    Sets the date on device

    Note: setting date on device requires root

    Parameters
    date Date : specify a particular date; will use host date if null

    Throws
    DeviceNotAvailableException

    setDeviceOwner

    public boolean setDeviceOwner (String componentName, 
                    int userId)

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

    Parameters
    componentName String : of device admin to be device owner.

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

    Returns
    boolean True if it is successful, false otherwise.

    Throws
    DeviceNotAvailableException

    setDeviceState

    public void setDeviceState ( TestDeviceState deviceState)

    Update the device's state.

    Parameters
    deviceState TestDeviceState : the TestDeviceState

    setEmulatorOutputStream

    public void setEmulatorOutputStream ( SizeLimitedOutputStream output)

    For emulator set SizeLimitedOutputStream to log output

    Parameters
    output SizeLimitedOutputStream : to log the output

    setEmulatorProcess

    public void setEmulatorProcess (Process p)

    Sets the Process , when this device is an emulator.

    Parameters
    p Process

    setFastbootEnabled

    public void setFastbootEnabled (boolean fastbootEnabled)

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

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

    Parameters
    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

    Parameters
    newDevice IDevice : the IDevice

    setOptions

    public void setOptions ( TestDeviceOptions options)

    Set the TestDeviceOptions for the device

    Parameters
    options TestDeviceOptions

    setProperty

    public boolean setProperty (String propKey, 
                    String propValue)

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

    Parameters
    propKey String : The key targeted to be set.

    propValue String : The property value to be set.

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

    Throws
    DeviceNotAvailableException

    setRecovery

    public void setRecovery ( IDeviceRecovery recovery)

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

    Parameters
    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

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

    Parameters
    namespace String

    key String

    value String

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

    Parameters
    userId int

    namespace String

    key String

    value String

    Throws
    DeviceNotAvailableException

    setUseFastbootErase

    public void setUseFastbootErase (boolean useFastbootErase)

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

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

    Parameters
    userId int : of the user to start in the background

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

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

    Parameters
    userId int : of the user to start in the background

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

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

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

    Parameters
    userId int : of the user to stop.

    Returns
    boolean true if the user was successfully stopped.

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

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

    Returns
    boolean true if the user was successfully stopped.

    Throws
    DeviceNotAvailableException

    switchToAdbTcp

    public String switchToAdbTcp ()

    Switch device to adb-over-tcp mode.

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

    Throws
    DeviceNotAvailableException

    switchToAdbUsb

    public boolean switchToAdbUsb ()

    Switch device to adb over usb mode.

    Returns
    boolean true if switch was successful, false otherwise.

    Throws
    DeviceNotAvailableException

    switchUser

    public boolean switchUser (int userId)

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

    Parameters
    userId int

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

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

    Parameters
    userId int

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

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

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

    Parameters
    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

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

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

    Returns
    Bugreport

    unencryptDevice

    public boolean unencryptDevice ()

    Unencrypts the device.

    Unencrypting the device may cause device to be wiped and may reboot device. This method will block until device is available and ready for testing. Requires fastboot inorder to wipe the userdata partition.

    Returns
    boolean true if successful.

    Throws
    DeviceNotAvailableException

    uninstallPackage

    public String uninstallPackage (String packageName)

    Uninstall an Android package from device.

    Parameters
    packageName String : the Android package to uninstall

    Returns
    String a String with an error code, or null if success.

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

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

    Throws
    DeviceNotAvailableException

    waitForBootComplete

    public boolean waitForBootComplete (long timeOut)

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

    Parameters
    timeOut long : time in msecs to wait for the flag to be set

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

    Throws
    DeviceNotAvailableException

    waitForDeviceAvailable

    public void waitForDeviceAvailable ()

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

    Throws
    DeviceNotAvailableException

    waitForDeviceAvailable

    public void waitForDeviceAvailable (long waitTime)

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

    Parameters
    waitTime long : the time in ms to wait

    Throws
    DeviceNotAvailableException

    waitForDeviceInRecovery

    public boolean waitForDeviceInRecovery (long waitTime)

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

    Parameters
    waitTime long : the time in ms to wait

    Returns
    boolean true if device boots into recovery before time expires. false otherwise

    waitForDeviceNotAvailable

    public boolean waitForDeviceNotAvailable (long waitTime)

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

    Parameters
    waitTime long : the time in ms to wait

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

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

    Parameters
    waitTime long : the time in ms to wait

    Throws
    DeviceNotAvailableException

    waitForDeviceShell

    public boolean waitForDeviceShell (long waitTime)

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

    Parameters
    waitTime long : the time in ms to wait

    Returns
    boolean true if device becomes responsive before waitTime elapses.

    Protected methods

    checkApiLevelAgainst

    protected void checkApiLevelAgainst (String feature, 
                    int strictMinLevel)

    Parameters
    feature String

    strictMinLevel int

    createRebootDeviceAction

    protected NativeDevice.RebootDeviceAction createRebootDeviceAction (String into)

    Create a RebootDeviceAction to be used when performing a reboot action.

    Parameters
    into String : the bootloader name to reboot into, or null to just reboot the device.

    Returns
    NativeDevice.RebootDeviceAction the created RebootDeviceAction .

    doAdbReboot

    protected void doAdbReboot (String into)

    Perform a adb reboot.

    Parameters
    into String : the bootloader name to reboot into, or null to just reboot the device.

    Throws
    DeviceNotAvailableException

    ensureRuntimePermissionSupported

    protected void ensureRuntimePermissionSupported ()

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

    Throws
    DeviceNotAvailableException

    getBugreportInternal

    protected InputStreamSource getBugreportInternal ()

    Returns
    InputStreamSource

    getBugreportzInternal

    protected File getBugreportzInternal ()

    Internal Helper method to get the bugreportz zip file as a ERROR(/File) .

    Returns
    File

    getRunUtil

    protected IRunUtil getRunUtil ()

    Get the RunUtil instance to use.

    Returns
    IRunUtil

    internalGetProperty

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

    Fetch a device property, from the ddmlib cache by default, and falling back to either `adb shell getprop` or `fastboot getvar` depending on whether the device is in Fastboot or not.

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

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

    Throws
    DeviceNotAvailableException

    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.

    Parameters
    localFile File

    entry IFileEntry

    Returns
    boolean

    performDeviceAction

    protected boolean performDeviceAction (String actionDescription, 
                    com.android.tradefed.device.NativeDevice.DeviceAction action, 
                    int retryAttempts)

    Performs an action on this device. Attempts to recover device and optionally retry command if action fails.

    Parameters
    actionDescription String : a short description of action to be performed. Used for logging purposes only.

    action com.android.tradefed.device.NativeDevice.DeviceAction : the action to be performed

    retryAttempts int : the retry attempts to make for action if it fails but recovery succeeds

    Returns
    boolean true if action was performed successfully

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

    Throws
    DeviceNotAvailableException

    prePostBootSetup

    protected void prePostBootSetup ()

    Allows each device type (AndroidNativeDevice, TestDevice) to override this method for specific post boot setup.

    Throws
    DeviceNotAvailableException

    setClock

    protected void setClock (Clock clock)

    Set the Clock instance to use.

    Parameters
    clock Clock

    setLogStartDelay

    protected void setLogStartDelay (int delay)

    Sets the time in ms to wait before starting logcat capture for a online device.

    Parameters
    delay int : the delay in ms

    waitForDeviceNotAvailable

    protected void waitForDeviceNotAvailable (String operationDesc, 
                    long time)

    Parameters
    operationDesc String

    time long