1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.tradefed.device; 17 18 import com.android.ddmlib.IDevice; 19 import com.android.ddmlib.IShellOutputReceiver; 20 import com.android.ddmlib.Log.LogLevel; 21 import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner; 22 import com.android.tradefed.build.IBuildInfo; 23 import com.android.tradefed.command.remote.DeviceDescriptor; 24 import com.android.tradefed.device.ITestDevice.MountPointInfo; 25 import com.android.tradefed.device.ITestDevice.RecoveryMode; 26 import com.android.tradefed.device.connection.AbstractConnection; 27 import com.android.tradefed.log.ITestLogger; 28 import com.android.tradefed.result.ITestLifeCycleReceiver; 29 import com.android.tradefed.result.InputStreamSource; 30 import com.android.tradefed.targetprep.TargetSetupError; 31 import com.android.tradefed.util.CommandResult; 32 import com.android.tradefed.util.MultiMap; 33 import com.android.tradefed.util.ProcessInfo; 34 import com.android.tradefed.util.TimeUtil; 35 36 import com.google.errorprone.annotations.MustBeClosed; 37 38 import java.io.File; 39 import java.io.OutputStream; 40 import java.util.Collection; 41 import java.util.Date; 42 import java.util.List; 43 import java.util.Map; 44 import java.util.Set; 45 import java.util.concurrent.TimeUnit; 46 47 import javax.annotation.Nullable; 48 49 /** 50 * Provides an reliable and slightly higher level API to a ddmlib {@link IDevice}. 51 * <p/> 52 * Retries device commands for a configurable amount, and provides a device recovery 53 * interface for devices which are unresponsive. 54 */ 55 public interface INativeDevice { 56 57 /** 58 * Default value when API Level cannot be detected 59 */ 60 public final static int UNKNOWN_API_LEVEL = -1; 61 62 /** 63 * Set the {@link TestDeviceOptions} for the device 64 */ setOptions(TestDeviceOptions options)65 public void setOptions(TestDeviceOptions options); 66 67 /** 68 * Returns a reference to the associated ddmlib {@link IDevice}. 69 * <p/> 70 * A new {@link IDevice} may be allocated by DDMS each time the device disconnects and 71 * reconnects from adb. Thus callers should not keep a reference to the {@link IDevice}, 72 * because that reference may become stale. 73 * 74 * @return the {@link IDevice} 75 */ getIDevice()76 public IDevice getIDevice(); 77 78 /** 79 * Convenience method to get serial number of this device. 80 * 81 * @return the {@link String} serial number 82 */ getSerialNumber()83 public String getSerialNumber(); 84 85 /** For device management purpose track the serial we use for referencing the device. */ setTrackingSerial(String trackingSerial)86 public void setTrackingSerial(String trackingSerial); 87 88 /** For device management purpose get the serial used to track the device. */ getTrackingSerial()89 public default String getTrackingSerial() { 90 return getSerialNumber(); 91 } 92 93 /** Returns the fastboot mode serial number. */ getFastbootSerialNumber()94 public String getFastbootSerialNumber(); 95 96 /** 97 * Retrieve the given property value from the device. 98 * 99 * @param name the property name 100 * @return the property value or <code>null</code> if it does not exist 101 * @throws DeviceNotAvailableException 102 */ getProperty(String name)103 public String getProperty(String name) throws DeviceNotAvailableException; 104 105 /** 106 * Returns integer value of the given property from the device. 107 * 108 * @param name the property name 109 * @param defaultValue default value to return if property is empty or doesn't exist. 110 * @return the property value or {@code defaultValue} if the property is empty, doesn't exist, 111 * or doesn't have an integer value. 112 */ getIntProperty(String name, long defaultValue)113 public long getIntProperty(String name, long defaultValue) throws DeviceNotAvailableException; 114 115 /** 116 * Returns boolean value of the given property. 117 * 118 * @param name the property name 119 * @param defaultValue default value to return if property is empty or doesn't exist. 120 * @return {@code true} if the property has value {@code "1"}, {@code "y"}, {@code "yes"}, 121 * {@code "on"}, or {@code "true"}, {@code false} if the property has value of {@code "0"}, 122 * {@code "n"}, {@code "no"}, {@code "off"}, {@code "false"}, or {@code defaultValue} 123 * otherwise. 124 */ getBooleanProperty(String name, boolean defaultValue)125 public boolean getBooleanProperty(String name, boolean defaultValue) 126 throws DeviceNotAvailableException; 127 128 /** 129 * Sets the given property value on the device. Requires adb root is true. 130 * 131 * @param propKey The key targeted to be set. 132 * @param propValue The property value to be set. 133 * @return returns <code>True</code> if the setprop command was successful, False otherwise. 134 * @throws DeviceNotAvailableException 135 */ setProperty(String propKey, String propValue)136 public boolean setProperty(String propKey, String propValue) throws DeviceNotAvailableException; 137 138 /** 139 * Retrieve the given fastboot variable value from the device. 140 * 141 * @param variableName the variable name 142 * @return the property value or <code>null</code> if it does not exist 143 * @throws DeviceNotAvailableException, UnsupportedOperationException 144 */ getFastbootVariable(String variableName)145 public String getFastbootVariable(String variableName) 146 throws DeviceNotAvailableException, UnsupportedOperationException; 147 148 /** 149 * Convenience method to get the bootloader version of this device. 150 * <p/> 151 * Will attempt to retrieve bootloader version from the device's current state. (ie if device 152 * is in fastboot mode, it will attempt to retrieve version from fastboot) 153 * 154 * @return the {@link String} bootloader version or <code>null</code> if it cannot be found 155 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 156 * recovered. 157 */ getBootloaderVersion()158 public String getBootloaderVersion() throws DeviceNotAvailableException; 159 160 /** 161 * Convenience method to get baseband (radio) version of this device. Getting the radio version 162 * is device specific, so it might not return the correct information for all devices. This 163 * method relies on the gsm.version.baseband propery to return the correct version information. 164 * This is not accurate for some CDMA devices and the version returned here might not match 165 * the version reported from fastboot and might not return the version for the CDMA radio. 166 * TL;DR this method only reports accurate version if the gsm.version.baseband property is the 167 * same as the version returned by <code>fastboot getvar version-baseband</code>. 168 * 169 * @return the {@link String} baseband version or <code>null</code> if it cannot be determined 170 * (device has no radio or version string cannot be read) 171 * @throws DeviceNotAvailableException if the connection with the device is lost and cannot 172 * be recovered. 173 */ getBasebandVersion()174 public String getBasebandVersion() throws DeviceNotAvailableException; 175 176 /** 177 * Convenience method to get the product type of this device. 178 * <p/> 179 * This method will work if device is in either adb or fastboot mode. 180 * 181 * @return the {@link String} product type name. Will not be null 182 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 183 * recovered, or if product type can not be determined 184 */ getProductType()185 public String getProductType() throws DeviceNotAvailableException; 186 187 /** 188 * Convenience method to get the product variant of this device. 189 * <p/> 190 * This method will work if device is in either adb or fastboot mode. 191 * 192 * @return the {@link String} product variant name or <code>null</code> if it cannot be 193 * determined 194 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 195 * recovered. 196 */ getProductVariant()197 public String getProductVariant() throws DeviceNotAvailableException; 198 199 /** 200 * Convenience method to get the product type of this device when its in fastboot mode. 201 * <p/> 202 * This method should only be used if device should be in fastboot. Its a bit safer variant 203 * than the generic {@link #getProductType()} method in this case, because ITestDevice 204 * will know to recover device into fastboot if device is in incorrect state or is 205 * unresponsive. 206 * 207 * @return the {@link String} product type name or <code>null</code> if it cannot be determined 208 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 209 * recovered. 210 */ getFastbootProductType()211 public String getFastbootProductType() throws DeviceNotAvailableException; 212 213 /** 214 * Convenience method to get the product type of this device when its in fastboot mode. 215 * <p/> 216 * This method should only be used if device should be in fastboot. Its a bit safer variant 217 * than the generic {@link #getProductType()} method in this case, because ITestDevice 218 * will know to recover device into fastboot if device is in incorrect state or is 219 * unresponsive. 220 * 221 * @return the {@link String} product type name or <code>null</code> if it cannot be determined 222 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 223 * recovered. 224 */ getFastbootProductVariant()225 public String getFastbootProductVariant() throws DeviceNotAvailableException; 226 227 /** 228 * Retrieve the alias of the build that the device is currently running. 229 * 230 * <p>Build alias is usually a more readable string than build id (typically a number for 231 * Nexus builds). For example, final Android 4.2 release has build alias JDQ39, and build id 232 * 573038 233 * @return the build alias or fall back to build id if it could not be retrieved 234 * @throws DeviceNotAvailableException 235 */ getBuildAlias()236 public String getBuildAlias() throws DeviceNotAvailableException; 237 238 /** 239 * Retrieve the build the device is currently running. 240 * 241 * @return the build id or {@link IBuildInfo#UNKNOWN_BUILD_ID} if it could not be retrieved 242 * @throws DeviceNotAvailableException 243 */ getBuildId()244 public String getBuildId() throws DeviceNotAvailableException; 245 246 /** 247 * Retrieve the build flavor for the device. 248 * 249 * @return the build flavor or null if it could not be retrieved 250 * @throws DeviceNotAvailableException 251 */ getBuildFlavor()252 public String getBuildFlavor() throws DeviceNotAvailableException; 253 254 /** 255 * Executes the given adb shell command, retrying multiple times if command fails. 256 * <p/> 257 * A simpler form of 258 * {@link #executeShellCommand(String, IShellOutputReceiver, long, TimeUnit, int)} with 259 * default values. 260 * 261 * @param command the adb shell command to run 262 * @param receiver the {@link IShellOutputReceiver} to direct shell output to. 263 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 264 * recovered. 265 */ executeShellCommand(String command, IShellOutputReceiver receiver)266 public void executeShellCommand(String command, IShellOutputReceiver receiver) 267 throws DeviceNotAvailableException; 268 269 /** 270 * Executes a adb shell command, with more parameters to control command behavior. 271 * 272 * @see #executeShellCommand(String, IShellOutputReceiver) 273 * @param command the adb shell command to run 274 * @param receiver the {@link IShellOutputReceiver} to direct shell output to. 275 * @param maxTimeToOutputShellResponse the maximum amount of time during which the command is 276 * allowed to not output any response; unit as specified in <code>timeUnit</code> 277 * @param timeUnit unit for <code>maxTimeToOutputShellResponse</code> 278 * @param retryAttempts the maximum number of times to retry command if it fails due to a 279 * exception. DeviceNotResponsiveException will be thrown if <var>retryAttempts</var> 280 * are performed without success. 281 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 282 * recovered. 283 * @see TimeUtil 284 */ executeShellCommand(String command, IShellOutputReceiver receiver, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)285 public void executeShellCommand(String command, IShellOutputReceiver receiver, 286 long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts) 287 throws DeviceNotAvailableException; 288 289 /** 290 * Executes a adb shell command, with more parameters to control command behavior. 291 * 292 * @see #executeShellCommand(String, IShellOutputReceiver) 293 * @param command the adb shell command to run 294 * @param receiver the {@link IShellOutputReceiver} to direct shell output to. 295 * @param maxTimeoutForCommand the maximum timeout for the command to complete; unit as 296 * specified in <code>timeUnit</code> 297 * @param maxTimeToOutputShellResponse the maximum amount of time during which the command is 298 * allowed to not output any response; unit as specified in <code>timeUnit</code> 299 * @param timeUnit unit for <code>maxTimeToOutputShellResponse</code> 300 * @param retryAttempts the maximum number of times to retry command if it fails due to a 301 * exception. DeviceNotResponsiveException will be thrown if <var>retryAttempts</var> are 302 * performed without success. 303 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 304 * recovered. 305 * @see TimeUtil 306 */ executeShellCommand( String command, IShellOutputReceiver receiver, long maxTimeoutForCommand, long maxTimeToOutputShellResponse, TimeUnit timeUnit, int retryAttempts)307 public void executeShellCommand( 308 String command, 309 IShellOutputReceiver receiver, 310 long maxTimeoutForCommand, 311 long maxTimeToOutputShellResponse, 312 TimeUnit timeUnit, 313 int retryAttempts) 314 throws DeviceNotAvailableException; 315 316 /** 317 * Helper method which executes a adb shell command and returns output as a {@link String}. 318 * 319 * @param command the adb shell command to run 320 * @return the shell output 321 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 322 * recovered. 323 */ executeShellCommand(String command)324 public String executeShellCommand(String command) throws DeviceNotAvailableException; 325 326 /** 327 * Helper method which executes a adb shell command and returns the results as a {@link 328 * CommandResult} properly populated with the command status output, stdout and stderr. 329 * 330 * @param command The command that should be run. 331 * @return The result in {@link CommandResult}. 332 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 333 * recovered. 334 */ executeShellV2Command(String command)335 public CommandResult executeShellV2Command(String command) throws DeviceNotAvailableException; 336 337 /** 338 * Helper method which executes an adb shell command and returns the results as a {@link 339 * CommandResult} properly populated with the command status output, stdout and stderr. 340 * 341 * @param command The command that should be run. 342 * @param pipeAsInput A {@link File} that will be piped as input to the command, or null. 343 * @return The result in {@link CommandResult}. 344 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 345 * recovered. 346 */ executeShellV2Command(String command, File pipeAsInput)347 public CommandResult executeShellV2Command(String command, File pipeAsInput) 348 throws DeviceNotAvailableException; 349 350 /** 351 * Helper method which executes an adb shell command and returns the results as a {@link 352 * CommandResult} properly populated with the command status output and stderr. stdout is 353 * directed to the specified stream. 354 * 355 * @param command The command that should be run. 356 * @param pipeToOutput {@link OutputStream} where the std output will be redirected, or null. 357 * @return The result in {@link CommandResult}. 358 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 359 * recovered. 360 */ executeShellV2Command(String command, OutputStream pipeToOutput)361 public CommandResult executeShellV2Command(String command, OutputStream pipeToOutput) 362 throws DeviceNotAvailableException; 363 364 /** 365 * Executes a adb shell command, with more parameters to control command behavior. 366 * 367 * @see #executeShellV2Command(String) 368 * @param command the adb shell command to run 369 * @param maxTimeoutForCommand the maximum timeout for the command to complete; unit as 370 * specified in <code>timeUnit</code> 371 * @param timeUnit unit for <code>maxTimeToOutputShellResponse</code> 372 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 373 * recovered. 374 * @see TimeUtil 375 */ executeShellV2Command( String command, final long maxTimeoutForCommand, final TimeUnit timeUnit)376 public CommandResult executeShellV2Command( 377 String command, final long maxTimeoutForCommand, final TimeUnit timeUnit) 378 throws DeviceNotAvailableException; 379 380 /** 381 * Executes a adb shell command, with more parameters to control command behavior. 382 * 383 * @see #executeShellV2Command(String) 384 * @param command the adb shell command to run 385 * @param maxTimeoutForCommand the maximum timeout for the command to complete; unit as 386 * specified in <code>timeUnit</code> 387 * @param timeUnit unit for <code>maxTimeToOutputShellResponse</code> 388 * @param retryAttempts the maximum number of times to retry command if it fails due to a 389 * exception. DeviceNotResponsiveException will be thrown if <var>retryAttempts</var> are 390 * performed without success. 391 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 392 * recovered. 393 * @see TimeUtil 394 */ executeShellV2Command( String command, final long maxTimeoutForCommand, final TimeUnit timeUnit, int retryAttempts)395 public CommandResult executeShellV2Command( 396 String command, 397 final long maxTimeoutForCommand, 398 final TimeUnit timeUnit, 399 int retryAttempts) 400 throws DeviceNotAvailableException; 401 402 /** 403 * Executes a adb shell command, with more parameters to control command behavior. 404 * 405 * @see #executeShellV2Command(String) 406 * @param command the adb shell command to run 407 * @param pipeAsInput A {@link File} that will be piped as input to the command, or null. 408 * @param pipeToOutput {@link OutputStream} where the std output will be redirected, or null. 409 * @param maxTimeoutForCommand the maximum timeout for the command to complete; unit as 410 * specified in <code>timeUnit</code> 411 * @param timeUnit unit for <code>maxTimeToOutputShellResponse</code> 412 * @param retryAttempts the maximum number of times to retry command if it fails due to a 413 * exception. DeviceNotResponsiveException will be thrown if <var>retryAttempts</var> are 414 * performed without success. 415 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 416 * recovered. 417 * @see TimeUtil 418 */ executeShellV2Command( String command, File pipeAsInput, OutputStream pipeToOutput, final long maxTimeoutForCommand, final TimeUnit timeUnit, int retryAttempts)419 public CommandResult executeShellV2Command( 420 String command, 421 File pipeAsInput, 422 OutputStream pipeToOutput, 423 final long maxTimeoutForCommand, 424 final TimeUnit timeUnit, 425 int retryAttempts) 426 throws DeviceNotAvailableException; 427 428 /** 429 * Executes a adb shell command, with more parameters to control command behavior. 430 * 431 * @see #executeShellV2Command(String) 432 * @param command the adb shell command to run 433 * @param pipeAsInput A {@link File} that will be piped as input to the command, or null. 434 * @param pipeToOutput {@link OutputStream} where the std output will be redirected, or null. 435 * @param pipeToError {@link OutputStream} where the std error will be redirected, or null. 436 * @param maxTimeoutForCommand the maximum timeout for the command to complete; unit as 437 * specified in <code>timeUnit</code> 438 * @param timeUnit unit for <code>maxTimeToOutputShellResponse</code> 439 * @param retryAttempts the maximum number of times to retry command if it fails due to a 440 * exception. DeviceNotResponsiveException will be thrown if <var>retryAttempts</var> are 441 * performed without success. 442 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 443 * recovered. 444 * @see TimeUtil 445 */ executeShellV2Command( String command, File pipeAsInput, OutputStream pipeToOutput, OutputStream pipeToError, final long maxTimeoutForCommand, final TimeUnit timeUnit, int retryAttempts)446 public CommandResult executeShellV2Command( 447 String command, 448 File pipeAsInput, 449 OutputStream pipeToOutput, 450 OutputStream pipeToError, 451 final long maxTimeoutForCommand, 452 final TimeUnit timeUnit, 453 int retryAttempts) 454 throws DeviceNotAvailableException; 455 456 /** 457 * Helper method which executes a adb command as a system command. 458 * <p/> 459 * {@link #executeShellCommand(String)} should be used instead wherever possible, as that 460 * method provides better failure detection and performance. 461 * 462 * @param commandArgs the adb command and arguments to run 463 * @return the stdout from command. <code>null</code> if command failed to execute. 464 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 465 * recovered. 466 */ executeAdbCommand(String... commandArgs)467 public String executeAdbCommand(String... commandArgs) throws DeviceNotAvailableException; 468 469 /** 470 * Helper method which executes a adb command as a system command with a specified timeout. 471 * 472 * <p>{@link #executeShellCommand(String)} should be used instead wherever possible, as that 473 * method provides better failure detection and performance. 474 * 475 * @param timeout the time in milliseconds before the device is considered unresponsive, 0L for 476 * no timeout 477 * @param commandArgs the adb command and arguments to run 478 * @return the stdout from command. <code>null</code> if command failed to execute. 479 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 480 * recovered. 481 */ executeAdbCommand(long timeout, String... commandArgs)482 public String executeAdbCommand(long timeout, String... commandArgs) 483 throws DeviceNotAvailableException; 484 485 /** 486 * Helper method which executes a adb command as a system command with a specified timeout. 487 * 488 * <p>{@link #executeShellCommand(String)} should be used instead wherever possible, as that 489 * method provides better failure detection and performance. 490 * 491 * @param timeout the time in milliseconds before the device is considered unresponsive, 0L for 492 * no timeout 493 * @param envMap environment to set for the command 494 * @param commandArgs the adb command and arguments to run 495 * @return the stdout from command. <code>null</code> if command failed to execute. 496 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 497 * recovered. 498 */ executeAdbCommand(long timeout, Map<String, String> envMap, String... commandArgs)499 public String executeAdbCommand(long timeout, Map<String, String> envMap, String... commandArgs) 500 throws DeviceNotAvailableException; 501 502 /** 503 * Helper method which executes a fastboot command as a system command with a default timeout of 504 * 2 minutes. 505 * 506 * <p>Expected to be used when device is already in fastboot mode. 507 * 508 * @param commandArgs the fastboot command and arguments to run 509 * @return the CommandResult containing output of command 510 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 511 * recovered. 512 */ executeFastbootCommand(String... commandArgs)513 public CommandResult executeFastbootCommand(String... commandArgs) 514 throws DeviceNotAvailableException; 515 516 /** 517 * Helper method which executes a fastboot command as a system command. 518 * <p/> 519 * Expected to be used when device is already in fastboot mode. 520 * 521 * @param timeout the time in milliseconds before the command expire 522 * @param commandArgs the fastboot command and arguments to run 523 * @return the CommandResult containing output of command 524 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 525 * recovered. 526 */ executeFastbootCommand(long timeout, String... commandArgs)527 public CommandResult executeFastbootCommand(long timeout, String... commandArgs) 528 throws DeviceNotAvailableException; 529 530 /** 531 * Helper method which executes a long running fastboot command as a system command. 532 * <p/> 533 * Identical to {@link #executeFastbootCommand(String...)} except uses a longer timeout. 534 * 535 * @param commandArgs the fastboot command and arguments to run 536 * @return the CommandResult containing output of command 537 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 538 * recovered. 539 */ executeLongFastbootCommand(String... commandArgs)540 public CommandResult executeLongFastbootCommand(String... commandArgs) 541 throws DeviceNotAvailableException; 542 543 /** 544 * Helper method which executes a long running fastboot command as a system command with system 545 * environment variables. 546 * 547 * <p>Identical to {@link #executeFastbootCommand(String...)} except uses a longer timeout. 548 * 549 * @param envVarMap the system environment variables that the fastboot command run with 550 * @param commandArgs the fastboot command and arguments to run 551 * @return the CommandResult containing output of command 552 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 553 * recovered. 554 */ executeLongFastbootCommand( Map<String, String> envVarMap, String... commandArgs)555 public CommandResult executeLongFastbootCommand( 556 Map<String, String> envVarMap, String... commandArgs) 557 throws DeviceNotAvailableException; 558 559 /** 560 * Get whether to use fastboot erase or fastboot format to wipe a partition on the device. 561 * 562 * @return {@code true} if fastboot erase will be used or {@code false} if fastboot format will 563 * be used. 564 * @see #fastbootWipePartition(String) 565 */ getUseFastbootErase()566 public boolean getUseFastbootErase(); 567 568 /** 569 * Set whether to use fastboot erase or fastboot format to wipe a partition on the device. 570 * 571 * @param useFastbootErase {@code true} if fastboot erase should be used or {@code false} if 572 * fastboot format should be used. 573 * @see #fastbootWipePartition(String) 574 */ setUseFastbootErase(boolean useFastbootErase)575 public void setUseFastbootErase(boolean useFastbootErase); 576 577 /** 578 * Helper method which wipes a partition for the device. 579 * <p/> 580 * If {@link #getUseFastbootErase()} is {@code true}, then fastboot erase will be used to wipe 581 * the partition. The device must then create a filesystem the next time the device boots. 582 * Otherwise, fastboot format is used which will create a new filesystem on the device. 583 * <p/> 584 * Expected to be used when device is already in fastboot mode. 585 * 586 * @param partition the partition to wipe 587 * @return the CommandResult containing output of command 588 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 589 * recovered. 590 */ fastbootWipePartition(String partition)591 public CommandResult fastbootWipePartition(String partition) throws DeviceNotAvailableException; 592 593 /** 594 * Runs instrumentation tests, and provides device recovery. 595 * 596 * <p>If connection with device is lost before test run completes, and recovery succeeds, all 597 * listeners will be informed of testRunFailed and "false" will be returned. The test command 598 * will not be rerun. It is left to callers to retry if necessary. 599 * 600 * <p>If connection with device is lost before test run completes, and recovery fails, all 601 * listeners will be informed of testRunFailed and DeviceNotAvailableException will be thrown. 602 * 603 * @param runner the {@link IRemoteAndroidTestRunner} which runs the tests 604 * @param listeners the test result listeners 605 * @return <code>true</code> if test command completed. <code>false</code> if it failed to 606 * complete due to device communication exception, but recovery succeeded 607 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 608 * recovered. ie test command failed to complete and recovery failed. 609 */ runInstrumentationTests( IRemoteAndroidTestRunner runner, Collection<ITestLifeCycleReceiver> listeners)610 public boolean runInstrumentationTests( 611 IRemoteAndroidTestRunner runner, Collection<ITestLifeCycleReceiver> listeners) 612 throws DeviceNotAvailableException; 613 614 /** 615 * Convenience method for performing {@link #runInstrumentationTests(IRemoteAndroidTestRunner, 616 * Collection)} with one or more listeners passed as parameters. 617 * 618 * @param runner the {@link IRemoteAndroidTestRunner} which runs the tests 619 * @param listeners the test result listener(s) 620 * @return <code>true</code> if test command completed. <code>false</code> if it failed to 621 * complete, but recovery succeeded 622 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 623 * recovered. ie test command failed to complete and recovery failed. 624 */ runInstrumentationTests( IRemoteAndroidTestRunner runner, ITestLifeCycleReceiver... listeners)625 public boolean runInstrumentationTests( 626 IRemoteAndroidTestRunner runner, ITestLifeCycleReceiver... listeners) 627 throws DeviceNotAvailableException; 628 629 /** 630 * Same as {@link ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, Collection)} but 631 * runs the test for the given user. 632 */ runInstrumentationTestsAsUser( IRemoteAndroidTestRunner runner, int userId, Collection<ITestLifeCycleReceiver> listeners)633 public boolean runInstrumentationTestsAsUser( 634 IRemoteAndroidTestRunner runner, 635 int userId, 636 Collection<ITestLifeCycleReceiver> listeners) 637 throws DeviceNotAvailableException; 638 639 /** 640 * Same as {@link ITestDevice#runInstrumentationTests(IRemoteAndroidTestRunner, 641 * ITestLifeCycleReceiver...)} but runs the test for a given user. 642 */ runInstrumentationTestsAsUser( IRemoteAndroidTestRunner runner, int userId, ITestLifeCycleReceiver... listeners)643 public boolean runInstrumentationTestsAsUser( 644 IRemoteAndroidTestRunner runner, int userId, ITestLifeCycleReceiver... listeners) 645 throws DeviceNotAvailableException; 646 647 /** 648 * Check whether platform on device supports runtime permission granting 649 * @return True if runtime permission are supported, false otherwise. 650 * @throws DeviceNotAvailableException 651 */ isRuntimePermissionSupported()652 public boolean isRuntimePermissionSupported() throws DeviceNotAvailableException; 653 654 /** 655 * Check whether platform on device supports app enumeration 656 * @return True if app enumeration is supported, false otherwise 657 * @throws DeviceNotAvailableException 658 */ isAppEnumerationSupported()659 public boolean isAppEnumerationSupported() throws DeviceNotAvailableException; 660 661 /** 662 * Check whether platform on device supports bypassing low target sdk block on app installs 663 * 664 * @return True if bypass low target sdk block is supported, false otherwise 665 * @throws DeviceNotAvailableException 666 */ isBypassLowTargetSdkBlockSupported()667 public boolean isBypassLowTargetSdkBlockSupported() throws DeviceNotAvailableException; 668 669 /** 670 * Retrieves a file off device. 671 * 672 * @param remoteFilePath the absolute path to file on device. 673 * @param localFile the local file to store contents in. If non-empty, contents will be 674 * replaced. 675 * @return <code>true</code> if file was retrieved successfully. <code>false</code> otherwise. 676 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 677 * recovered. 678 */ pullFile(String remoteFilePath, File localFile)679 public boolean pullFile(String remoteFilePath, File localFile) 680 throws DeviceNotAvailableException; 681 682 /** 683 * Retrieves a file off device. 684 * 685 * @param remoteFilePath the absolute path to file on device. 686 * @param localFile the local file to store contents in. If non-empty, contents will be 687 * replaced. 688 * @param userId The user id to pull from 689 * @return <code>true</code> if file was retrieved successfully. <code>false</code> otherwise. 690 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 691 * recovered. 692 */ pullFile(String remoteFilePath, File localFile, int userId)693 public boolean pullFile(String remoteFilePath, File localFile, int userId) 694 throws DeviceNotAvailableException; 695 696 /** 697 * Retrieves a file off device, stores it in a local temporary {@link File}, and returns that 698 * {@code File}. 699 * 700 * @param remoteFilePath the absolute path to file on device. 701 * @return A {@link File} containing the contents of the device file, or {@code null} if the 702 * copy failed for any reason (including problems with the host filesystem) 703 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 704 * recovered. 705 */ pullFile(String remoteFilePath)706 public File pullFile(String remoteFilePath) throws DeviceNotAvailableException; 707 708 /** 709 * Retrieves a file off device, stores it in a local temporary {@link File}, and returns that 710 * {@code File}. 711 * 712 * @param remoteFilePath the absolute path to file on device. 713 * @param userId The user id to pull from 714 * @return A {@link File} containing the contents of the device file, or {@code null} if the 715 * copy failed for any reason (including problems with the host filesystem) 716 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 717 * recovered. 718 */ pullFile(String remoteFilePath, int userId)719 public File pullFile(String remoteFilePath, int userId) throws DeviceNotAvailableException; 720 721 /** 722 * Retrieves a file off device, and returns the contents. 723 * 724 * @param remoteFilePath the absolute path to file on device. 725 * @return A {@link String} containing the contents of the device file, or {@code null} if the 726 * copy failed for any reason (including problems with the host filesystem) 727 */ pullFileContents(String remoteFilePath)728 public String pullFileContents(String remoteFilePath) throws DeviceNotAvailableException; 729 730 /** 731 * A convenience method to retrieve a file from the device's external storage, stores it in a 732 * local temporary {@link File}, and return a reference to that {@code File}. 733 * 734 * @param remoteFilePath the path to file on device, relative to the device's external storage 735 * mountpoint 736 * @return A {@link File} containing the contents of the device file, or {@code null} if the 737 * copy failed for any reason (including problems with the host filesystem) 738 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 739 * recovered. 740 */ pullFileFromExternal(String remoteFilePath)741 public File pullFileFromExternal(String remoteFilePath) throws DeviceNotAvailableException; 742 743 /** 744 * Recursively pull directory contents from device. 745 * 746 * @param deviceFilePath the absolute file path of the remote source 747 * @param localDir the local directory to pull files into 748 * @return <code>true</code> if file was pulled successfully. <code>false</code> otherwise. 749 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 750 * recovered. 751 */ pullDir(String deviceFilePath, File localDir)752 public boolean pullDir(String deviceFilePath, File localDir) 753 throws DeviceNotAvailableException; 754 755 /** 756 * Recursively pull directory contents from device. 757 * 758 * @param deviceFilePath the absolute file path of the remote source 759 * @param localDir the local directory to pull files into 760 * @param userId the user id to pull from 761 * @return <code>true</code> if file was pulled successfully. <code>false</code> otherwise. 762 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 763 * recovered. 764 */ pullDir(String deviceFilePath, File localDir, int userId)765 public boolean pullDir(String deviceFilePath, File localDir, int userId) 766 throws DeviceNotAvailableException; 767 768 /** 769 * Push a file to device. By default using a content provider. 770 * 771 * @param localFile the local file to push 772 * @param deviceFilePath the remote destination absolute file path 773 * @return <code>true</code> if file was pushed successfully. <code>false</code> otherwise. 774 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 775 * recovered. 776 */ pushFile(File localFile, String deviceFilePath)777 public boolean pushFile(File localFile, String deviceFilePath) 778 throws DeviceNotAvailableException; 779 780 /** 781 * Push a file to device. By default using a content provider. 782 * 783 * @param localFile the local file to push 784 * @param deviceFilePath the remote destination absolute file path 785 * @param userId the userId to push to 786 * @return <code>true</code> if file was pushed successfully. <code>false</code> otherwise. 787 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 788 * recovered. 789 */ pushFile(File localFile, String deviceFilePath, int userId)790 public boolean pushFile(File localFile, String deviceFilePath, int userId) 791 throws DeviceNotAvailableException; 792 793 /** 794 * Variant of {@link #pushFile(File, String)} which can optionally consider evaluating the need 795 * for the content provider. 796 * 797 * @param localFile the local file to push 798 * @param deviceFilePath the remote destination absolute file path 799 * @param evaluateContentProviderNeeded whether to check if we need the content provider 800 * @return <code>true</code> if file was pushed successfully. <code>false</code> otherwise. 801 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 802 * recovered. 803 */ pushFile( final File localFile, final String deviceFilePath, boolean evaluateContentProviderNeeded)804 public boolean pushFile( 805 final File localFile, 806 final String deviceFilePath, 807 boolean evaluateContentProviderNeeded) 808 throws DeviceNotAvailableException; 809 810 /** 811 * Push file created from a string to device 812 * 813 * @param contents the contents of the file to push 814 * @param deviceFilePath the remote destination absolute file path 815 * @return <code>true</code> if string was pushed successfully. <code>false</code> otherwise. 816 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 817 * recovered. 818 */ pushString(String contents, String deviceFilePath)819 public boolean pushString(String contents, String deviceFilePath) 820 throws DeviceNotAvailableException; 821 822 /** 823 * Recursively push directory contents to device. 824 * 825 * @param localDir the local directory to push 826 * @param deviceFilePath the absolute file path of the remote destination 827 * @return <code>true</code> if file was pushed successfully. <code>false</code> otherwise. 828 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 829 * recovered. 830 */ pushDir(File localDir, String deviceFilePath)831 public boolean pushDir(File localDir, String deviceFilePath) 832 throws DeviceNotAvailableException; 833 834 /** 835 * Recursively push directory contents to device. 836 * 837 * @param localDir the local directory to push 838 * @param deviceFilePath the absolute file path of the remote destination 839 * @param userId the user id to push to 840 * @return <code>true</code> if file was pushed successfully. <code>false</code> otherwise. 841 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 842 * recovered. 843 */ pushDir(File localDir, String deviceFilePath, int userId)844 public boolean pushDir(File localDir, String deviceFilePath, int userId) 845 throws DeviceNotAvailableException; 846 847 /** 848 * Recursively push directory contents to device while excluding some directories that are 849 * filtered. 850 * 851 * @param localDir the local directory to push 852 * @param deviceFilePath the absolute file path of the remote destination 853 * @param excludedDirectories Set of excluded directories names that shouldn't be pushed. 854 * @return <code>true</code> if file was pushed successfully. <code>false</code> otherwise. 855 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 856 * recovered. 857 */ pushDir(File localDir, String deviceFilePath, Set<String> excludedDirectories)858 public boolean pushDir(File localDir, String deviceFilePath, Set<String> excludedDirectories) 859 throws DeviceNotAvailableException; 860 861 /** 862 * Incrementally syncs the contents of a local file directory to device. 863 * <p/> 864 * Decides which files to push by comparing timestamps of local files with their remote 865 * equivalents. Only 'newer' or non-existent files will be pushed to device. Thus overhead 866 * should be relatively small if file set on device is already up to date. 867 * <p/> 868 * Hidden files (with names starting with ".") will be ignored. 869 * <p/> 870 * Example usage: syncFiles("/tmp/files", "/sdcard") will created a /sdcard/files directory if 871 * it doesn't already exist, and recursively push the /tmp/files contents to /sdcard/files. 872 * 873 * @param localFileDir the local file directory containing files to recursively push. 874 * @param deviceFilePath the remote destination absolute file path root. All directories in thos 875 * file path must be readable. ie pushing to /data/local/tmp when adb is not root 876 * will fail 877 * @return <code>true</code> if files were synced successfully. <code>false</code> otherwise. 878 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 879 * recovered. 880 */ syncFiles(File localFileDir, String deviceFilePath)881 public boolean syncFiles(File localFileDir, String deviceFilePath) 882 throws DeviceNotAvailableException; 883 884 /** 885 * Helper method to determine if file on device exists. 886 * 887 * @param deviceFilePath the absolute path of file on device to check 888 * @return <code>true</code> if file exists, <code>false</code> otherwise. 889 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 890 * recovered. 891 */ doesFileExist(String deviceFilePath)892 public boolean doesFileExist(String deviceFilePath) throws DeviceNotAvailableException; 893 894 /** 895 * Helper method to delete a file or directory on the device. 896 * 897 * @param deviceFilePath The absolute path of the file on the device. 898 * @throws DeviceNotAvailableException 899 */ deleteFile(String deviceFilePath)900 public void deleteFile(String deviceFilePath) throws DeviceNotAvailableException; 901 902 /** 903 * Helper method to delete a file or directory on the device. 904 * 905 * @param deviceFilePath The absolute path of the file on the device. 906 * @param userId The user id to delete from 907 * @throws DeviceNotAvailableException 908 */ deleteFile(String deviceFilePath, int userId)909 public void deleteFile(String deviceFilePath, int userId) throws DeviceNotAvailableException; 910 911 /** 912 * Retrieve a reference to a remote file on device. 913 * 914 * @param path the file path to retrieve. Can be an absolute path or path relative to '/'. (ie 915 * both "/system" and "system" syntax is supported) 916 * @return the {@link IFileEntry} or <code>null</code> if file at given <var>path</var> cannot 917 * be found 918 * @throws DeviceNotAvailableException 919 */ getFileEntry(String path)920 public IFileEntry getFileEntry(String path) throws DeviceNotAvailableException; 921 922 /** 923 * Returns True if the file path on the device is an executable file, false otherwise. 924 * 925 * @throws DeviceNotAvailableException 926 */ isExecutable(String fullPath)927 public boolean isExecutable(String fullPath) throws DeviceNotAvailableException; 928 929 /** 930 * Return True if the path on the device is a directory, false otherwise. 931 * 932 * @throws DeviceNotAvailableException 933 */ isDirectory(String deviceFilePath)934 public boolean isDirectory(String deviceFilePath) throws DeviceNotAvailableException; 935 936 /** 937 * Alternative to using {@link IFileEntry} that sometimes won't work because of permissions. 938 * 939 * @param deviceFilePath is the path on the device where to do the search 940 * @return Array of string containing all the file in a path on the device. 941 * @throws DeviceNotAvailableException 942 */ getChildren(String deviceFilePath)943 public String[] getChildren(String deviceFilePath) throws DeviceNotAvailableException; 944 945 /** 946 * Helper method to determine amount of free space on device external storage. 947 * 948 * @return the amount of free space in KB 949 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 950 * recovered. 951 */ getExternalStoreFreeSpace()952 public long getExternalStoreFreeSpace() throws DeviceNotAvailableException; 953 954 /** 955 * Helper method to determine amount of free space on device partition. 956 * 957 * @return the amount of free space in KB 958 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 959 * recovered. 960 */ getPartitionFreeSpace(String partition)961 public long getPartitionFreeSpace(String partition) throws DeviceNotAvailableException; 962 963 /** 964 * Returns a mount point. 965 * <p/> 966 * Queries the device directly if the cached info in {@link IDevice} is not available. 967 * <p/> 968 * TODO: move this behavior to {@link IDevice#getMountPoint(String)} 969 * 970 * @param mountName the name of the mount point 971 * @return the mount point or <code>null</code> 972 * @see IDevice#getMountPoint(String) 973 */ getMountPoint(String mountName)974 public String getMountPoint(String mountName); 975 976 /** 977 * Returns a parsed version of the information in /proc/mounts on the device 978 * 979 * @return A {@link List} of {@link MountPointInfo} containing the information in "/proc/mounts" 980 */ getMountPointInfo()981 public List<MountPointInfo> getMountPointInfo() throws DeviceNotAvailableException; 982 983 /** 984 * Returns a {@link MountPointInfo} corresponding to the specified mountpoint path, or 985 * <code>null</code> if that path has nothing mounted or otherwise does not appear in 986 * /proc/mounts as a mountpoint. 987 * 988 * @return A {@link List} of {@link MountPointInfo} containing the information in "/proc/mounts" 989 * @see #getMountPointInfo() 990 */ getMountPointInfo(String mountpoint)991 public MountPointInfo getMountPointInfo(String mountpoint) throws DeviceNotAvailableException; 992 993 /** 994 * Start capturing logcat output from device in the background. 995 * <p/> 996 * Will have no effect if logcat output is already being captured. 997 * Data can be later retrieved via getLogcat. 998 * <p/> 999 * When the device is no longer in use, {@link #stopLogcat()} must be called. 1000 * <p/> 1001 * {@link #startLogcat()} and {@link #stopLogcat()} do not normally need to be called when 1002 * within a TF invocation context, as the TF framework will start and stop logcat. 1003 */ startLogcat()1004 public void startLogcat(); 1005 1006 /** 1007 * Stop capturing logcat output from device, and discard currently saved logcat data. 1008 * <p/> 1009 * Will have no effect if logcat output is not being captured. 1010 */ stopLogcat()1011 public void stopLogcat(); 1012 1013 /** 1014 * Deletes any accumulated logcat data. 1015 * <p/> 1016 * This is useful for cases when you want to ensure {@link ITestDevice#getLogcat()} only returns 1017 * log data produced after a certain point (such as after flashing a new device build, etc). 1018 */ clearLogcat()1019 public void clearLogcat(); 1020 1021 /** 1022 * Grabs a snapshot stream of the logcat data. 1023 * 1024 * <p>Works in two modes: 1025 * <li>If the logcat is currently being captured in the background, will return up to {@link 1026 * TestDeviceOptions#getMaxLogcatDataSize()} bytes of the current contents of the background 1027 * logcat capture 1028 * <li>Otherwise, will return a static dump of the logcat data if device is currently responding 1029 */ 1030 @MustBeClosed getLogcat()1031 public InputStreamSource getLogcat(); 1032 1033 /** 1034 * Grabs a snapshot stream of the last <code>maxBytes</code> of captured logcat data. 1035 * 1036 * <p>Useful for cases when you want to capture frequent snapshots of the captured logcat data 1037 * without incurring the potentially big disk space penalty of getting the entire {@link 1038 * #getLogcat()} snapshot. 1039 * 1040 * @param maxBytes the maximum amount of data to return. Should be an amount that can 1041 * comfortably fit in memory 1042 */ 1043 @MustBeClosed getLogcat(int maxBytes)1044 public InputStreamSource getLogcat(int maxBytes); 1045 1046 /** 1047 * Grabs a snapshot stream of captured logcat data starting the date provided. The time on the 1048 * device should be used {@link #getDeviceDate}. 1049 * 1050 * <p> 1051 * 1052 * @param date in millisecond since epoch format of when to start the snapshot until present. 1053 * (can be be obtained using 'date +%s') 1054 */ 1055 @MustBeClosed getLogcatSince(long date)1056 public InputStreamSource getLogcatSince(long date); 1057 1058 /** 1059 * Get a dump of the current logcat for device. Unlike {@link #getLogcat()}, this method will 1060 * always return a static dump of the logcat. 1061 * 1062 * <p>Has the disadvantage that nothing will be returned if device is not reachable. 1063 * 1064 * @return a {@link InputStreamSource} of the logcat data. An empty stream is returned if fail 1065 * to capture logcat data. 1066 */ 1067 @MustBeClosed getLogcatDump()1068 public InputStreamSource getLogcatDump(); 1069 1070 /** 1071 * Perform instructions to configure device for testing that after every boot. 1072 * <p/> 1073 * Should be called after device is fully booted/available 1074 * <p/> 1075 * In normal circumstances this method doesn't need to be called explicitly, as 1076 * implementations should perform these steps automatically when performing a reboot. 1077 * <p/> 1078 * Where it may need to be called is when device reboots due to other events (eg when a 1079 * fastboot update command has completed) 1080 * 1081 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1082 * recovered. 1083 */ postBootSetup()1084 public void postBootSetup() throws DeviceNotAvailableException; 1085 1086 /** 1087 * Reboots the device into bootloader mode. 1088 * <p/> 1089 * Blocks until device is in bootloader mode. 1090 * 1091 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1092 * recovered. 1093 */ rebootIntoBootloader()1094 public void rebootIntoBootloader() throws DeviceNotAvailableException; 1095 1096 /** 1097 * Returns true if device is in {@link TestDeviceState#FASTBOOT} or {@link 1098 * TestDeviceState#FASTBOOTD}. 1099 */ isStateBootloaderOrFastbootd()1100 public boolean isStateBootloaderOrFastbootd(); 1101 1102 /** 1103 * Reboots the device into adb mode. 1104 * <p/> 1105 * Blocks until device becomes available. 1106 * 1107 * @throws DeviceNotAvailableException if device is not available after reboot 1108 */ reboot()1109 public void reboot() throws DeviceNotAvailableException; 1110 1111 /** 1112 * Reboots the device into adb mode with given {@code reason} to be persisted across reboot. 1113 * 1114 * <p>Blocks until device becomes available. 1115 * 1116 * <p>Last reboot reason can be obtained by querying {@code sys.boot.reason} propety. 1117 * 1118 * @param reason a reason for this reboot, or {@code null} if no reason is specified. 1119 * @throws DeviceNotAvailableException if device is not available after reboot 1120 */ reboot(@ullable String reason)1121 public void reboot(@Nullable String reason) throws DeviceNotAvailableException; 1122 1123 /** 1124 * Reboots the device into fastbootd mode. 1125 * 1126 * <p>Blocks until device is in fastbootd mode. 1127 * 1128 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1129 * recovered. 1130 */ rebootIntoFastbootd()1131 public void rebootIntoFastbootd() throws DeviceNotAvailableException; 1132 1133 /** 1134 * Reboots only userspace part of device. 1135 * 1136 * <p>Blocks until device becomes available. 1137 * 1138 * <p>WARNING. Userspace reboot is currently under active development, use it on your own risk. 1139 * 1140 * @throws DeviceNotAvailableException if device is not available after reboot 1141 */ 1142 // TODO(ioffe): link to docs around userspace reboot when they are available. rebootUserspace()1143 public void rebootUserspace() throws DeviceNotAvailableException; 1144 1145 /** 1146 * Reboots the device into adb recovery mode. 1147 * <p/> 1148 * Blocks until device enters recovery 1149 * 1150 * @throws DeviceNotAvailableException if device is not available after reboot 1151 */ rebootIntoRecovery()1152 public void rebootIntoRecovery() throws DeviceNotAvailableException; 1153 1154 /** 1155 * Reboots the device into adb sideload mode (note that this is a special mode under recovery) 1156 * 1157 * <p>Blocks until device enters sideload mode 1158 * 1159 * @throws DeviceNotAvailableException if device is not in sideload after reboot 1160 */ rebootIntoSideload()1161 public void rebootIntoSideload() throws DeviceNotAvailableException; 1162 1163 /** 1164 * Reboots the device into adb sideload mode (note that this is a special mode under recovery) 1165 * 1166 * <p>Blocks until device enters sideload mode 1167 * 1168 * @param autoReboot whether to automatically reboot the device after sideload 1169 * @throws DeviceNotAvailableException if device is not in sideload after reboot 1170 */ rebootIntoSideload(boolean autoReboot)1171 public void rebootIntoSideload(boolean autoReboot) throws DeviceNotAvailableException; 1172 1173 /** 1174 * An alternate to {@link #reboot()} that only blocks until device is online ie visible to adb. 1175 * 1176 * @throws DeviceNotAvailableException if device is not available after reboot 1177 */ rebootUntilOnline()1178 public void rebootUntilOnline() throws DeviceNotAvailableException; 1179 1180 /** 1181 * An alternate to {@link #reboot()} that only blocks until device is online ie visible to adb. 1182 * 1183 * @param reason a reason for this reboot, or {@code null} if no reason is specified. 1184 * @throws DeviceNotAvailableException if device is not available after reboot 1185 * @see #reboot(String) 1186 */ rebootUntilOnline(@ullable String reason)1187 public void rebootUntilOnline(@Nullable String reason) throws DeviceNotAvailableException; 1188 1189 /** 1190 * An alternate to {@link #rebootUserspace()} ()} that only blocks until device is online ie 1191 * visible to adb. 1192 * 1193 * @throws DeviceNotAvailableException if device is not available after reboot 1194 */ rebootUserspaceUntilOnline()1195 public void rebootUserspaceUntilOnline() throws DeviceNotAvailableException; 1196 1197 /** 1198 * Issues a command to reboot device and returns on command complete and when device is no 1199 * longer visible to adb. 1200 * 1201 * @throws DeviceNotAvailableException 1202 */ nonBlockingReboot()1203 public void nonBlockingReboot() throws DeviceNotAvailableException; 1204 1205 /** 1206 * Turns on adb root. If the "enable-root" setting is "false", will log a message and 1207 * return without enabling root. 1208 * <p/> 1209 * Enabling adb root may cause device to disconnect from adb. This method will block until 1210 * device is available. 1211 * 1212 * @return <code>true</code> if successful. 1213 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1214 * recovered. 1215 */ enableAdbRoot()1216 public boolean enableAdbRoot() throws DeviceNotAvailableException; 1217 1218 /** 1219 * Turns off adb root. 1220 * <p/> 1221 * Disabling adb root may cause device to disconnect from adb. This method will block until 1222 * device is available. 1223 * 1224 * @return <code>true</code> if successful. 1225 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1226 * recovered. 1227 */ disableAdbRoot()1228 public boolean disableAdbRoot() throws DeviceNotAvailableException; 1229 1230 /** 1231 * @return <code>true</code> if device currently has adb root, <code>false</code> otherwise. 1232 * 1233 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1234 * recovered. 1235 */ isAdbRoot()1236 public boolean isAdbRoot() throws DeviceNotAvailableException; 1237 1238 /** 1239 * Unlocks the device if the device is in an encrypted state. 1240 * </p> 1241 * This method may restart the framework but will not call {@link #postBootSetup()}. Therefore, 1242 * the device might not be fully ready to be tested when this method returns. 1243 * 1244 * @return <code>true</code> if successful or if the device is unencrypted. 1245 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1246 * recovered. 1247 * @throws UnsupportedOperationException if encryption is not supported on the device. 1248 */ unlockDevice()1249 public boolean unlockDevice() throws DeviceNotAvailableException, 1250 UnsupportedOperationException; 1251 1252 /** 1253 * Returns if the device is encrypted. 1254 * 1255 * @return <code>true</code> if the device is encrypted. 1256 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1257 * recovered. 1258 */ isDeviceEncrypted()1259 public boolean isDeviceEncrypted() throws DeviceNotAvailableException; 1260 1261 /** 1262 * Returns if encryption is supported on the device. 1263 * 1264 * @return <code>true</code> if the device supports encryption. 1265 * @throws DeviceNotAvailableException 1266 */ isEncryptionSupported()1267 public boolean isEncryptionSupported() throws DeviceNotAvailableException; 1268 1269 /** 1270 * Waits for the device to be responsive and available for testing. 1271 * 1272 * @param waitTime the time in ms to wait 1273 * @throws DeviceNotAvailableException if device is still unresponsive after waitTime expires. 1274 * @return True if device is available, False if recovery is disabled and unavailable. 1275 */ waitForDeviceAvailable(final long waitTime)1276 public boolean waitForDeviceAvailable(final long waitTime) throws DeviceNotAvailableException; 1277 1278 /** 1279 * Waits for the device to be responsive and available for testing. Uses default timeout. 1280 * 1281 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1282 * recovered. 1283 * @return True if device is available, False if recovery is disabled and unavailable. 1284 */ waitForDeviceAvailable()1285 public boolean waitForDeviceAvailable() throws DeviceNotAvailableException; 1286 1287 /** 1288 * Waits for the device to be responsive and available without considering recovery path. 1289 * 1290 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1291 * recovered. 1292 * @return True if device is available, False if unavailable. 1293 */ waitForDeviceAvailableInRecoverPath(final long waitTime)1294 public boolean waitForDeviceAvailableInRecoverPath(final long waitTime) 1295 throws DeviceNotAvailableException; 1296 1297 /** 1298 * Blocks until device is visible via adb. 1299 * <p/> 1300 * Note the device may not necessarily be responsive to commands on completion. Use 1301 * {@link #waitForDeviceAvailable()} instead. 1302 * 1303 * @param waitTime the time in ms to wait 1304 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1305 * recovered. 1306 */ waitForDeviceOnline(final long waitTime)1307 public void waitForDeviceOnline(final long waitTime) throws DeviceNotAvailableException; 1308 1309 /** 1310 * Blocks until device is visible via adb. Uses default timeout 1311 * <p/> 1312 * Note the device may not necessarily be responsive to commands on completion. Use 1313 * {@link #waitForDeviceAvailable()} instead. 1314 * 1315 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1316 * recovered. 1317 */ waitForDeviceOnline()1318 public void waitForDeviceOnline() throws DeviceNotAvailableException; 1319 1320 /** 1321 * Blocks for the device to be not available ie missing from adb 1322 * 1323 * @param waitTime the time in ms to wait 1324 * @return <code>true</code> if device becomes not available before time expires. 1325 * <code>false</code> otherwise 1326 */ waitForDeviceNotAvailable(final long waitTime)1327 public boolean waitForDeviceNotAvailable(final long waitTime); 1328 1329 /** 1330 * Blocks until device is visible via fastboot. Use default timeout. 1331 * 1332 * @throws DeviceNotAvailableException if connection with device is lost and cannot be 1333 * recovered. 1334 */ waitForDeviceBootloader()1335 public void waitForDeviceBootloader() throws DeviceNotAvailableException; 1336 1337 /** 1338 * Blocks for the device to be in the 'adb recovery' state (note this is distinct from 1339 * {@link IDeviceRecovery}). 1340 * 1341 * @param waitTime the time in ms to wait 1342 * @return <code>true</code> if device boots into recovery before time expires. 1343 * <code>false</code> otherwise 1344 */ waitForDeviceInRecovery(final long waitTime)1345 public boolean waitForDeviceInRecovery(final long waitTime); 1346 1347 /** 1348 * Blocks for the device to be in the 'adb sideload' state 1349 * 1350 * @param waitTime the time in ms to wait 1351 * @return <code>true</code> if device boots into sideload before time expires. <code>false 1352 * </code> otherwise 1353 */ waitForDeviceInSideload(final long waitTime)1354 public boolean waitForDeviceInSideload(final long waitTime); 1355 1356 /** 1357 * Waits for device to be responsive to a basic adb shell command. 1358 * 1359 * @param waitTime the time in ms to wait 1360 * @return <code>true</code> if device becomes responsive before <var>waitTime</var> elapses. 1361 */ waitForDeviceShell(final long waitTime)1362 public boolean waitForDeviceShell(final long waitTime); 1363 1364 /** 1365 * Blocks until the device's boot complete flag is set. 1366 * 1367 * @param timeOut time in msecs to wait for the flag to be set 1368 * @return true if device's boot complete flag is set within the timeout 1369 * @throws DeviceNotAvailableException 1370 */ waitForBootComplete(long timeOut)1371 public boolean waitForBootComplete(long timeOut) throws DeviceNotAvailableException; 1372 1373 /** 1374 * Set the {@link IDeviceRecovery} to use for this device. Should be set when device is first 1375 * allocated. 1376 * 1377 * @param recovery the {@link IDeviceRecovery} 1378 */ setRecovery(IDeviceRecovery recovery)1379 public void setRecovery(IDeviceRecovery recovery); 1380 1381 /** 1382 * Set the current recovery mode to use for the device. 1383 * <p/> 1384 * Used to control what recovery method to use when a device communication problem is 1385 * encountered. Its recommended to only use this method sparingly when needed (for example, 1386 * when framework is down, etc 1387 * 1388 * @param mode whether 'recover till online only' mode should be on or not. 1389 */ setRecoveryMode(RecoveryMode mode)1390 public void setRecoveryMode(RecoveryMode mode); 1391 1392 /** 1393 * Get the current recovery mode used for the device. 1394 * 1395 * @return the current recovery mode used for the device. 1396 */ getRecoveryMode()1397 public RecoveryMode getRecoveryMode(); 1398 1399 /** 1400 * Get the device's state. 1401 */ getDeviceState()1402 public TestDeviceState getDeviceState(); 1403 1404 /** 1405 * @return <code>true</code> if device is connected to adb-over-tcp, <code>false</code> 1406 * otherwise. 1407 */ isAdbTcp()1408 public boolean isAdbTcp(); 1409 1410 /** 1411 * Switch device to adb-over-tcp mode. 1412 * 1413 * @return the tcp serial number or <code>null</code> if device could not be switched 1414 * @throws DeviceNotAvailableException 1415 */ switchToAdbTcp()1416 public String switchToAdbTcp() throws DeviceNotAvailableException; 1417 1418 /** 1419 * Switch device to adb over usb mode. 1420 * 1421 * @return <code>true</code> if switch was successful, <code>false</code> otherwise. 1422 * @throws DeviceNotAvailableException 1423 */ switchToAdbUsb()1424 public boolean switchToAdbUsb() throws DeviceNotAvailableException; 1425 1426 /** 1427 * Get the stream of emulator stdout and stderr 1428 * @return emulator output 1429 */ getEmulatorOutput()1430 public InputStreamSource getEmulatorOutput(); 1431 1432 /** 1433 * Close and delete the emulator output. 1434 */ stopEmulatorOutput()1435 public void stopEmulatorOutput(); 1436 1437 /** 1438 * Get the device API Level. Defaults to {@link #UNKNOWN_API_LEVEL}. 1439 * 1440 * @return an integer indicating the API Level of device 1441 * @throws DeviceNotAvailableException 1442 */ getApiLevel()1443 public int getApiLevel() throws DeviceNotAvailableException; 1444 1445 /** 1446 * Get the device's first launched API Level. Defaults to {@link #UNKNOWN_API_LEVEL}. 1447 * 1448 * @return an integer indicating the first launched API Level of device 1449 * @throws DeviceNotAvailableException 1450 */ getLaunchApiLevel()1451 public int getLaunchApiLevel() throws DeviceNotAvailableException; 1452 1453 /** 1454 * Check whether or not a feature is currently supported given a minimally supported level. This 1455 * method takes into account unreleased features yet, before API level is raised. 1456 * 1457 * @param strictMinLevel The strict min possible level that supports the feature. 1458 * @return True if the level is supported. False otherwise. 1459 * @throws DeviceNotAvailableException 1460 */ checkApiLevelAgainstNextRelease(int strictMinLevel)1461 public boolean checkApiLevelAgainstNextRelease(int strictMinLevel) 1462 throws DeviceNotAvailableException; 1463 1464 /** 1465 * Helper to get the time difference between the device and a given {@link Date}. Use Epoch time 1466 * internally. 1467 * 1468 * @return the difference in milliseconds 1469 */ getDeviceTimeOffset(Date date)1470 public long getDeviceTimeOffset(Date date) throws DeviceNotAvailableException; 1471 1472 /** 1473 * Sets the date on device 1474 * <p> 1475 * Note: setting date on device requires root 1476 * @param date specify a particular date; will use host date if <code>null</code> 1477 * @throws DeviceNotAvailableException 1478 */ setDate(Date date)1479 public void setDate(Date date) throws DeviceNotAvailableException; 1480 1481 /** 1482 * Return the date of the device in millisecond since epoch. 1483 * 1484 * <p> 1485 * 1486 * @return the date of the device in epoch format. 1487 * @throws DeviceNotAvailableException 1488 */ getDeviceDate()1489 public long getDeviceDate() throws DeviceNotAvailableException; 1490 1491 /** 1492 * Make the system partition on the device writable. May reboot the device. 1493 * @throws DeviceNotAvailableException 1494 */ remountSystemWritable()1495 public void remountSystemWritable() throws DeviceNotAvailableException; 1496 1497 /** 1498 * Make the vendor partition on the device writable. May reboot the device. 1499 * 1500 * @throws DeviceNotAvailableException 1501 */ remountVendorWritable()1502 public void remountVendorWritable() throws DeviceNotAvailableException; 1503 1504 /** 1505 * Make the system partition on the device read-only. May reboot the device. 1506 * 1507 * @throws DeviceNotAvailableException 1508 */ remountSystemReadOnly()1509 public void remountSystemReadOnly() throws DeviceNotAvailableException; 1510 1511 /** 1512 * Make the vendor partition on the device read-only. May reboot the device. 1513 * 1514 * @throws DeviceNotAvailableException 1515 */ remountVendorReadOnly()1516 public void remountVendorReadOnly() throws DeviceNotAvailableException; 1517 1518 /** 1519 * Returns the key type used to sign the device image 1520 * <p> 1521 * Typically Android devices may be signed with test-keys (like in AOSP) or release-keys 1522 * (controlled by individual device manufacturers) 1523 * @return The signing key if found, null otherwise. 1524 * @throws DeviceNotAvailableException 1525 */ getBuildSigningKeys()1526 public String getBuildSigningKeys() throws DeviceNotAvailableException; 1527 1528 /** 1529 * Collects and log ANRs from the device. 1530 * 1531 * @param logger an {@link ITestLogger} to log the ANRs. 1532 * @return True if the logging was successful, false otherwise. 1533 */ logAnrs(ITestLogger logger)1534 public boolean logAnrs(ITestLogger logger) throws DeviceNotAvailableException; 1535 1536 /** 1537 * Get the device class. 1538 * 1539 * @return the {@link String} device class. 1540 */ getDeviceClass()1541 public String getDeviceClass(); 1542 1543 /** 1544 * Extra steps for device specific required setup that will be executed on the device prior to 1545 * the invocation flow. 1546 * 1547 * @param info The {@link IBuildInfo} of the device. 1548 * @param attributes The attributes stored in the invocation context 1549 * @throws TargetSetupError 1550 * @throws DeviceNotAvailableException 1551 */ preInvocationSetup(IBuildInfo info, MultiMap<String, String> attributes)1552 public default void preInvocationSetup(IBuildInfo info, MultiMap<String, String> attributes) 1553 throws TargetSetupError, DeviceNotAvailableException { 1554 // Empty default implementation. 1555 } 1556 1557 /** 1558 * Extra steps for device specific required clean up that will be executed after the invocation 1559 * is done. 1560 * 1561 * @deprecated Use {@link #postInvocationTearDown(Throwable)} instead. 1562 */ 1563 @Deprecated postInvocationTearDown()1564 public default void postInvocationTearDown() { 1565 postInvocationTearDown(null); 1566 } 1567 1568 /** 1569 * Extra steps for device specific required clean up that will be executed after the invocation 1570 * is done. 1571 * 1572 * @param invocationException if any, the final exception raised by the invocation failure. 1573 */ postInvocationTearDown(Throwable invocationException)1574 public void postInvocationTearDown(Throwable invocationException); 1575 1576 /** 1577 * Return true if the device is headless (no screen), false otherwise. 1578 */ isHeadless()1579 public boolean isHeadless() throws DeviceNotAvailableException; 1580 1581 /** 1582 * Return a {@link DeviceDescriptor} from the device information to get info on it without 1583 * passing the actual device object. 1584 */ getDeviceDescriptor()1585 public DeviceDescriptor getDeviceDescriptor(); 1586 1587 /** 1588 * Return a {@link DeviceDescriptor} from the device information to get info on it without 1589 * passing the actual device object. 1590 * 1591 * @param shortDescriptor Whether or not to limit descriptor to bare minimum info 1592 */ getDeviceDescriptor(boolean shortDescriptor)1593 public DeviceDescriptor getDeviceDescriptor(boolean shortDescriptor); 1594 1595 /** 1596 * Returns a cached {@link DeviceDescriptor} if the device is allocated, otherwise returns the 1597 * current {@link DeviceDescriptor}. 1598 */ getCachedDeviceDescriptor()1599 public DeviceDescriptor getCachedDeviceDescriptor(); 1600 1601 /** 1602 * Returns a cached {@link DeviceDescriptor} if the device is allocated, otherwise returns the 1603 * current {@link DeviceDescriptor}. 1604 * 1605 * @param shortDescriptor Whether or not to limit descriptor to bare minimum info 1606 */ getCachedDeviceDescriptor(boolean shortDescriptor)1607 public DeviceDescriptor getCachedDeviceDescriptor(boolean shortDescriptor); 1608 1609 /** 1610 * Helper method runs the "pidof" and "stat" command and returns {@link ProcessInfo} object with 1611 * PID and process start time of the given process. 1612 * 1613 * @param processName the proces name String. 1614 * @return ProcessInfo of given processName 1615 */ getProcessByName(String processName)1616 public ProcessInfo getProcessByName(String processName) throws DeviceNotAvailableException; 1617 1618 /** 1619 * Helper method collects the boot history map with boot time and boot reason. 1620 * 1621 * @return Map of boot time (UTC time in second since Epoch) and boot reason 1622 */ getBootHistory()1623 public Map<Long, String> getBootHistory() throws DeviceNotAvailableException; 1624 1625 /** 1626 * Helper method collects the boot history map with boot time and boot reason since the given 1627 * time since epoch from device and the time unit specified. The current device utcEpochTime in 1628 * Millisecond can be obtained by method {@link #getDeviceDate}. 1629 * 1630 * @param utcEpochTime the device time since Epoch. 1631 * @param timeUnit the time unit <code>TimeUnit</code>. 1632 * @return Map of boot time (UTC time in second since Epoch) and boot reason 1633 */ getBootHistorySince(long utcEpochTime, TimeUnit timeUnit)1634 public Map<Long, String> getBootHistorySince(long utcEpochTime, TimeUnit timeUnit) 1635 throws DeviceNotAvailableException; 1636 1637 /** 1638 * Returns the pid of the service or null if something went wrong. 1639 * 1640 * @param process The proces name String. 1641 */ getProcessPid(String process)1642 public String getProcessPid(String process) throws DeviceNotAvailableException; 1643 1644 /** 1645 * Helper method to check whether device soft-restarted since the UTC time since epoch from 1646 * device and its {@link TimeUnit}. Soft-Restart refers to system_server restarted outside of a 1647 * device hard reboot (for example: requested reboot). The current device utcEpochTime in 1648 * Milliseccond can be obtained by method {@link #getDeviceDate}. 1649 * 1650 * @param utcEpochTime the device time in second since epoch. 1651 * @param timeUnit the time unit <code>TimeUnit</code> for the given utcEpochTime. 1652 * @return {@code true} if device soft-restarted 1653 * @throws RuntimeException if device has abnormal boot reason 1654 * @throws DeviceNotAvailableException 1655 */ deviceSoftRestartedSince(long utcEpochTime, TimeUnit timeUnit)1656 public boolean deviceSoftRestartedSince(long utcEpochTime, TimeUnit timeUnit) 1657 throws DeviceNotAvailableException; 1658 1659 /** 1660 * Helper method to check if device soft-restarted by comparing current system_server with 1661 * previous system_server {@link ProcessInfo}. Use {@link #getProcessByName} to get {@link 1662 * ProcessInfo}. 1663 * 1664 * @param prevSystemServerProcess the previous system_server process {@link ProcessInfo}. 1665 * @return {@code true} if device soft-restarted 1666 * @throws RuntimeException if device has abnormal boot reason 1667 * @throws DeviceNotAvailableException 1668 */ deviceSoftRestarted(ProcessInfo prevSystemServerProcess)1669 public boolean deviceSoftRestarted(ProcessInfo prevSystemServerProcess) 1670 throws DeviceNotAvailableException; 1671 1672 /** 1673 * Log a message in the logcat of the device. This is a safe call that will not throw even if 1674 * the logging fails. 1675 * 1676 * @param tag The tag under which we log our message in the logcat. 1677 * @param level The debug level of the message in the logcat. 1678 * @param format The message format. 1679 * @param args the args to be replaced via String.format(). 1680 */ logOnDevice(String tag, LogLevel level, String format, Object... args)1681 public void logOnDevice(String tag, LogLevel level, String format, Object... args); 1682 1683 /** Returns total physical memory size in bytes or -1 in case of internal error */ getTotalMemory()1684 public long getTotalMemory(); 1685 1686 /** Returns the current battery level of a device or Null if battery level unavailable. */ getBattery()1687 public Integer getBattery(); 1688 1689 /** 1690 * Returns the last time Tradefed APIs triggered a reboot in milliseconds since EPOCH as 1691 * returned by {@link System#currentTimeMillis()}. 1692 */ getLastExpectedRebootTimeMillis()1693 public long getLastExpectedRebootTimeMillis(); 1694 1695 /** 1696 * Fetch and return the list of tombstones from the devices. Requires root. 1697 * 1698 * <p>method is best-effort so if one tombstone fails to be pulled for any reason it will be 1699 * missing from the list. Only a {@link DeviceNotAvailableException} will terminate the method 1700 * early. 1701 * 1702 * @return A list of tombstone files, empty if no tombstone. 1703 * @see <a href="https://source.android.com/devices/tech/debug">Tombstones documentation</a> 1704 */ getTombstones()1705 public List<File> getTombstones() throws DeviceNotAvailableException; 1706 1707 /** Returns the connection associated with the device. */ getConnection()1708 public AbstractConnection getConnection(); 1709 1710 /** 1711 * Check if debugfs is mounted. 1712 * 1713 * @return {@code true} if debugfs is mounted 1714 * @throws DeviceNotAvailableException 1715 */ isDebugfsMounted()1716 public boolean isDebugfsMounted() throws DeviceNotAvailableException; 1717 1718 /** 1719 * Mount debugfs. 1720 * 1721 * @throws DeviceNotAvailableException 1722 */ mountDebugfs()1723 public void mountDebugfs() throws DeviceNotAvailableException; 1724 1725 /** 1726 * Unmount debugfs. 1727 * 1728 * @throws DeviceNotAvailableException 1729 */ unmountDebugfs()1730 public void unmountDebugfs() throws DeviceNotAvailableException; 1731 } 1732