Search in sources :

Example 1 with IDevice

use of com.android.ddmlib.IDevice in project buck by facebook.

the class AdbHelper method startActivity.

@SuppressForbidden
public int startActivity(SourcePathResolver pathResolver, HasInstallableApk hasInstallableApk, @Nullable String activity, boolean waitForDebugger) throws IOException, InterruptedException {
    // Might need the package name and activities from the AndroidManifest.
    Path pathToManifest = pathResolver.getAbsolutePath(hasInstallableApk.getApkInfo().getManifestPath());
    AndroidManifestReader reader = DefaultAndroidManifestReader.forPath(hasInstallableApk.getProjectFilesystem().resolve(pathToManifest));
    if (activity == null) {
        // Get list of activities that show up in the launcher.
        List<String> launcherActivities = reader.getLauncherActivities();
        // Sanity check.
        if (launcherActivities.isEmpty()) {
            console.printBuildFailure("No launchable activities found.");
            return 1;
        } else if (launcherActivities.size() > 1) {
            console.printBuildFailure("Default activity is ambiguous.");
            return 1;
        }
        // Construct a component for the '-n' argument of 'adb shell am start'.
        activity = reader.getPackage() + "/" + launcherActivities.get(0);
    } else if (!activity.contains("/")) {
        // If no package name was provided, assume the one in the manifest.
        activity = reader.getPackage() + "/" + activity;
    }
    final String activityToRun = activity;
    PrintStream stdOut = console.getStdOut();
    stdOut.println(String.format("Starting activity %s...", activityToRun));
    StartActivityEvent.Started started = StartActivityEvent.started(hasInstallableApk.getBuildTarget(), activityToRun);
    getBuckEventBus().post(started);
    boolean success = adbCall(new AdbHelper.AdbCallable() {

        @Override
        public boolean call(IDevice device) throws Exception {
            String err = deviceStartActivity(device, activityToRun, waitForDebugger);
            if (err != null) {
                console.printBuildFailure(err);
                return false;
            } else {
                return true;
            }
        }

        @Override
        public String toString() {
            return "start activity";
        }
    }, false);
    getBuckEventBus().post(StartActivityEvent.finished(started, success));
    return success ? 0 : 1;
}
Also used : Path(java.nio.file.Path) PrintStream(java.io.PrintStream) StartActivityEvent(com.facebook.buck.event.StartActivityEvent) IDevice(com.android.ddmlib.IDevice) AdbCommandRejectedException(com.android.ddmlib.AdbCommandRejectedException) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) InstallException(com.android.ddmlib.InstallException) TimeoutException(com.android.ddmlib.TimeoutException) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) ExecutionException(java.util.concurrent.ExecutionException) ShellCommandUnresponsiveException(com.android.ddmlib.ShellCommandUnresponsiveException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 2 with IDevice

use of com.android.ddmlib.IDevice in project buck by facebook.

the class AdbHelper method adbCall.

/**
   * Execute an {@link AdbCallable} for all matching devices. This functions performs device
   * filtering based on three possible arguments:
   *
   *  -e (emulator-only) - only emulators are passing the filter
   *  -d (device-only) - only real devices are passing the filter
   *  -s (serial) - only device/emulator with specific serial number are passing the filter
   *
   *  If more than one device matches the filter this function will fail unless multi-install
   *  mode is enabled (-x). This flag is used as a marker that user understands that multiple
   *  devices will be used to install the apk if needed.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
@SuppressForbidden
public boolean adbCall(AdbCallable adbCallable, boolean quiet) throws InterruptedException {
    List<IDevice> devices;
    try (SimplePerfEvent.Scope ignored = SimplePerfEvent.scope(buckEventBus, "set_up_adb_call")) {
        devices = getDevices(quiet);
        if (devices.size() == 0) {
            return false;
        }
    }
    int adbThreadCount = options.getAdbThreadCount();
    if (adbThreadCount <= 0) {
        adbThreadCount = devices.size();
    }
    // Start executions on all matching devices.
    List<ListenableFuture<Boolean>> futures = Lists.newArrayList();
    ListeningExecutorService executorService = listeningDecorator(newMultiThreadExecutor(new CommandThreadFactory(getClass().getSimpleName()), adbThreadCount));
    for (final IDevice device : devices) {
        futures.add(executorService.submit(adbCallable.forDevice(device)));
    }
    // Wait for all executions to complete or fail.
    List<Boolean> results = null;
    try {
        results = Futures.allAsList(futures).get();
    } catch (ExecutionException ex) {
        console.printBuildFailure("Failed: " + adbCallable);
        ex.printStackTrace(console.getStdErr());
        return false;
    } catch (InterruptedException e) {
        try {
            Futures.allAsList(futures).cancel(true);
        } catch (CancellationException ignored) {
        // Rethrow original InterruptedException instead.
        }
        Thread.currentThread().interrupt();
        throw e;
    } finally {
        MostExecutors.shutdownOrThrow(executorService, 10, TimeUnit.MINUTES, new InterruptionFailedException("Failed to shutdown ExecutorService."));
    }
    int successCount = 0;
    for (Boolean result : results) {
        if (result) {
            successCount++;
        }
    }
    int failureCount = results.size() - successCount;
    // Report results.
    if (successCount > 0 && !quiet) {
        console.printSuccess(String.format("Successfully ran %s on %d device(s)", adbCallable, successCount));
    }
    if (failureCount > 0) {
        console.printBuildFailure(String.format("Failed to %s on %d device(s).", adbCallable, failureCount));
    }
    return failureCount == 0;
}
Also used : CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) IDevice(com.android.ddmlib.IDevice) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) SimplePerfEvent(com.facebook.buck.event.SimplePerfEvent) ExecutionException(java.util.concurrent.ExecutionException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 3 with IDevice

use of com.android.ddmlib.IDevice in project buck by facebook.

the class AdbHelper method installApk.

/**
   * Install apk on all matching devices. This functions performs device
   * filtering based on three possible arguments:
   *
   *  -e (emulator-only) - only emulators are passing the filter
   *  -d (device-only) - only real devices are passing the filter
   *  -s (serial) - only device/emulator with specific serial number are passing the filter
   *
   *  If more than one device matches the filter this function will fail unless multi-install
   *  mode is enabled (-x). This flag is used as a marker that user understands that multiple
   *  devices will be used to install the apk if needed.
   */
@SuppressForbidden
public boolean installApk(SourcePathResolver pathResolver, HasInstallableApk hasInstallableApk, boolean installViaSd, boolean quiet) throws InterruptedException {
    Optional<ExopackageInfo> exopackageInfo = hasInstallableApk.getApkInfo().getExopackageInfo();
    if (exopackageInfo.isPresent()) {
        return new ExopackageInstaller(pathResolver, context, this, hasInstallableApk).install(quiet);
    }
    InstallEvent.Started started = InstallEvent.started(hasInstallableApk.getBuildTarget());
    if (!quiet) {
        getBuckEventBus().post(started);
    }
    File apk = pathResolver.getAbsolutePath(hasInstallableApk.getApkInfo().getApkPath()).toFile();
    boolean success = adbCall(new AdbHelper.AdbCallable() {

        @Override
        public boolean call(IDevice device) throws Exception {
            return installApkOnDevice(device, apk, installViaSd, quiet);
        }

        @Override
        @SuppressForbidden
        public String toString() {
            return String.format("install apk %s", hasInstallableApk.getBuildTarget().toString());
        }
    }, quiet);
    if (!quiet) {
        AdbHelper.tryToExtractPackageNameFromManifest(pathResolver, hasInstallableApk.getApkInfo());
        getBuckEventBus().post(InstallEvent.finished(started, success, Optional.empty(), Optional.of(AdbHelper.tryToExtractPackageNameFromManifest(pathResolver, hasInstallableApk.getApkInfo()))));
    }
    return success;
}
Also used : IDevice(com.android.ddmlib.IDevice) AdbCommandRejectedException(com.android.ddmlib.AdbCommandRejectedException) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) InstallException(com.android.ddmlib.InstallException) TimeoutException(com.android.ddmlib.TimeoutException) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) ExecutionException(java.util.concurrent.ExecutionException) ShellCommandUnresponsiveException(com.android.ddmlib.ShellCommandUnresponsiveException) InstallEvent(com.facebook.buck.event.InstallEvent) ExopackageInfo(com.facebook.buck.rules.ExopackageInfo) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden) File(java.io.File) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 4 with IDevice

use of com.android.ddmlib.IDevice in project buck by facebook.

the class ApkInstallStep method getDescription.

@Override
public String getDescription(ExecutionContext context) {
    StringBuilder builder = new StringBuilder();
    try {
        AdbHelper adbHelper = AdbHelper.get(context, true);
        for (IDevice device : adbHelper.getDevices(true)) {
            if (builder.length() != 0) {
                builder.append("\n");
            }
            builder.append("adb -s ");
            builder.append(device.getSerialNumber());
            builder.append(" install ");
            builder.append(hasInstallableApk.getApkInfo().getApkPath().toString());
        }
    } catch (InterruptedException e) {
    }
    return builder.toString();
}
Also used : IDevice(com.android.ddmlib.IDevice)

Example 5 with IDevice

use of com.android.ddmlib.IDevice in project buck by facebook.

the class AndroidInstrumentationTest method runTests.

@Override
public ImmutableList<Step> runTests(ExecutionContext executionContext, TestRunningOptions options, SourcePathResolver pathResolver, TestReportingCallback testReportingCallback) {
    Preconditions.checkArgument(executionContext.getAdbOptions().isPresent());
    if (executionContext.getAdbOptions().get().isMultiInstallModeEnabled()) {
        throw new HumanReadableException("Running android instrumentation tests with multiple devices is not supported.");
    }
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    Path pathToTestOutput = getPathToTestOutputDirectory();
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), pathToTestOutput));
    steps.add(new ApkInstallStep(pathResolver, apk));
    if (apk instanceof AndroidInstrumentationApk) {
        steps.add(new ApkInstallStep(pathResolver, ((AndroidInstrumentationApk) apk).getApkUnderTest()));
    }
    AdbHelper adb = AdbHelper.get(executionContext, true);
    IDevice device;
    try {
        device = adb.getSingleDevice();
    } catch (InterruptedException e) {
        throw new HumanReadableException("Unable to get connected device.");
    }
    steps.add(getInstrumentationStep(pathResolver, executionContext.getPathToAdbExecutable(), Optional.of(getProjectFilesystem().resolve(pathToTestOutput)), Optional.of(device.getSerialNumber()), Optional.empty(), getFilterString(options), Optional.empty()));
    return steps.build();
}
Also used : SourcePath(com.facebook.buck.rules.SourcePath) Path(java.nio.file.Path) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) PathSourcePath(com.facebook.buck.rules.PathSourcePath) HumanReadableException(com.facebook.buck.util.HumanReadableException) ImmutableList(com.google.common.collect.ImmutableList) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep) IDevice(com.android.ddmlib.IDevice) Step(com.facebook.buck.step.Step) MakeCleanDirectoryStep(com.facebook.buck.step.fs.MakeCleanDirectoryStep)

Aggregations

IDevice (com.android.ddmlib.IDevice)76 Test (org.junit.Test)17 AndroidDebugBridge (com.android.ddmlib.AndroidDebugBridge)11 AdbOptions (com.facebook.buck.step.AdbOptions)11 TargetDeviceOptions (com.facebook.buck.step.TargetDeviceOptions)11 NotNull (org.jetbrains.annotations.NotNull)10 Client (com.android.ddmlib.Client)6 File (java.io.File)6 AndroidVersion (com.android.sdklib.AndroidVersion)5 SuppressForbidden (com.facebook.buck.annotations.SuppressForbidden)5 TIntArrayList (gnu.trove.TIntArrayList)5 Nullable (org.jetbrains.annotations.Nullable)5 InstallException (com.android.ddmlib.InstallException)4 AvdInfo (com.android.sdklib.internal.avd.AvdInfo)4 ExecutionException (java.util.concurrent.ExecutionException)4 AdbCommandRejectedException (com.android.ddmlib.AdbCommandRejectedException)3 ShellCommandUnresponsiveException (com.android.ddmlib.ShellCommandUnresponsiveException)3 TimeoutException (com.android.ddmlib.TimeoutException)3 BuckEventBus (com.facebook.buck.event.BuckEventBus)3 TestConsole (com.facebook.buck.testutil.TestConsole)3