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