com.android.ddmlib.IDevice Java Examples

The following examples show how to use com.android.ddmlib.IDevice. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlazeAndroidRunConfigurationRunner.java    From intellij with Apache License 2.0 7 votes vote down vote up
private static String canDebug(
    DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) {
  // If we are debugging on a device, then the app needs to be debuggable
  for (ListenableFuture<IDevice> future : deviceFutures.get()) {
    if (!future.isDone()) {
      // this is an emulator, and we assume that all emulators are debuggable
      continue;
    }
    IDevice device = Futures.getUnchecked(future);
    if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
      return AndroidBundle.message(
          "android.cannot.debug.noDebugPermissions", moduleName, device.getName());
    }
  }
  return null;
}
 
Example #2
Source File: AdbHelperTest.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Verify that filtering by serial number works. */
@Test
public void testDeviceFilterBySerial() {
  IDevice[] devices =
      new IDevice[] {
        createRealDevice("1", IDevice.DeviceState.ONLINE),
        createEmulator("2", IDevice.DeviceState.ONLINE),
        createRealDevice("3", IDevice.DeviceState.ONLINE),
        createEmulator("4", IDevice.DeviceState.ONLINE)
      };

  for (int i = 0; i < devices.length; i++) {
    AdbHelper myAdbHelper =
        createAdbHelper(
            createAdbOptions(),
            new TargetDeviceOptions(false, false, Optional.of(devices[i].getSerialNumber())));
    List<IDevice> filteredDevices = myAdbHelper.filterDevices(devices);
    assertNotNull(filteredDevices);
    assertEquals(1, filteredDevices.size());
    assertSame(devices[i], filteredDevices.get(0));
  }
}
 
Example #3
Source File: IncomingCallEvent.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
@Override
public Object onEventReceived(IDevice device) {
	String senderNumber = "";
	for(int i = 0; i < 8; i++)
		senderNumber += ThreadLocalRandom.current().nextInt(0, 9 + 1);
	
	EmulatorConsole emulatorConsole = EmulatorConsole.getConsole(device);
	LoggerHelper.logEvent(MyLevel.ADB_EVENT, adbEventFormat(toString(), String.format("incomingCall(%s)", senderNumber)));
	//call a random number
	emulatorConsole.call(senderNumber);
	//let it ring for 3 seconds
	try {
		Thread.sleep(3000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	//cancel call
	emulatorConsole.cancelCall(senderNumber);
	return null;
}
 
Example #4
Source File: EventLogParser.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Inits the parser for a specific Device.
 * <p/>
 * This methods reads the event-log-tags located on the device to find out
 * what tags are being written to the event log and what their format is.
 * @param device The device.
 * @return <code>true</code> if success, <code>false</code> if failure or cancellation.
 */
public boolean init(IDevice device) {
    // read the event tag map file on the device.
    try {
        device.executeShellCommand("cat " + EVENT_TAG_MAP_FILE, //$NON-NLS-1$
                new MultiLineReceiver() {
            @Override
            public void processNewLines(String[] lines) {
                for (String line : lines) {
                    processTagLine(line);
                }
            }
            @Override
            public boolean isCancelled() {
                return false;
            }
        });
    } catch (Exception e) {
        // catch all possible exceptions and return false.
        return false;
    }

    return true;
}
 
Example #5
Source File: AdbHelperTest.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that multi-install is not enabled and multiple devices pass the filter null is returned.
 * Also verify that if multiple devices are passing the filter and multi-install mode is enabled
 * they all appear in resulting list.
 */
@Test
public void testDeviceFilterMultipleDevices() {
  IDevice[] devices =
      new IDevice[] {
        createEmulator("1", IDevice.DeviceState.ONLINE),
        createEmulator("2", IDevice.DeviceState.ONLINE),
        createRealDevice("4", IDevice.DeviceState.ONLINE),
        createRealDevice("5", IDevice.DeviceState.ONLINE)
      };

  List<IDevice> filteredDevicesNoMultiInstall = basicAdbHelper.filterDevices(devices);
  assertNotNull(filteredDevicesNoMultiInstall);
  assertEquals(devices.length, filteredDevicesNoMultiInstall.size());

  AdbHelper myAdbHelper = createAdbHelper(createAdbOptions(true), new TargetDeviceOptions());
  List<IDevice> filteredDevices = myAdbHelper.filterDevices(devices);
  assertNotNull(filteredDevices);
  assertEquals(devices.length, filteredDevices.size());
}
 
Example #6
Source File: MyDeviceChooser.java    From ADBWIFI with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Object getValueAt(int rowIndex, int columnIndex) {
  if (rowIndex >= myDevices.length) {
    return null;
  }
  IDevice device = myDevices[rowIndex];
  switch (columnIndex) {
    case DEVICE_NAME_COLUMN_INDEX:
      return device;
    case SERIAL_COLUMN_INDEX:
      return device.getSerialNumber();
    case DEVICE_STATE_COLUMN_INDEX:
      return getDeviceState(device);
    case COMPATIBILITY_COLUMN_INDEX:
      return new CanRunOnDeviceCompat(myMinSdkVersion, myProjectTarget, myRequiredHardwareFeatures, device).get();
  }
  return null;
}
 
Example #7
Source File: HJAdb.java    From HJMirror with MIT License 6 votes vote down vote up
/**
 * Start and find Devices.
 */
public IDevice[] startAndFind() throws Exception {
    if (adb == null) {
        AndroidDebugBridge.init(false);
        DdmPreferences.setTimeOut(20000);
        adb = AndroidDebugBridge.createBridge(getAdbExec(), true);
        if (adb == null) {
            throw new Exception("Adb initilized failed!");
        }
    }
    if (adb.hasInitialDeviceList()) {
        IDevice[] devices = adb.getDevices();
        if (devices != null) {
            return devices;
        } else {
            return new IDevice[]{};
        }
    }
    return new IDevice[]{};
}
 
Example #8
Source File: InitView.java    From HJMirror with MIT License 6 votes vote down vote up
private void refreshDevices(IDevice[] devices) {
    this.devices = devices;
    if (devices.length == 0) {
        table.setEnabled(false);
        table.setOnItemClickListener(null);
        tableModel.setRowCount(0);
    } else {
        table.setEnabled(true);
        table.setOnItemClickListener(this);
        tableModel.setRowCount(0);
        for (IDevice device : devices) {
            Vector<String> row = new Vector<>();
            row.add(device.getName());
            row.add(device.getState().name());
            row.add(textDoubleClick);
            tableModel.addRow(row);
        }
    }
}
 
Example #9
Source File: MyDeviceChooser.java    From ADB-Duang with MIT License 6 votes vote down vote up
@Override
    @Nullable
    public Object getValueAt(int rowIndex, int columnIndex) {
      if (rowIndex >= myDevices.length) {
        return null;
      }
      IDevice device = myDevices[rowIndex];
      switch (columnIndex) {
        case DEVICE_NAME_COLUMN_INDEX:
          return device;
        case SERIAL_COLUMN_INDEX:
          return device.getSerialNumber();
        case DEVICE_STATE_COLUMN_INDEX:
          return getDeviceState(device);
//        case COMPATIBILITY_COLUMN_INDEX:
//          return new CanRunOnDeviceCompat(myMinSdkVersion, myProjectTarget, myRequiredHardwareFeatures, device).get();
      }
      return null;
    }
 
Example #10
Source File: MyDeviceChooser.java    From ADB-Duang with MIT License 6 votes vote down vote up
private void resetSelection(@NotNull String[] selectedSerials) {
  MyDeviceTableModel model = (MyDeviceTableModel)myDeviceTable.getModel();
  Set<String> selectedSerialsSet = new HashSet<String>();
  Collections.addAll(selectedSerialsSet, selectedSerials);
  IDevice[] myDevices = model.myDevices;
  ListSelectionModel selectionModel = myDeviceTable.getSelectionModel();
  boolean cleared = false;

  for (int i = 0, n = myDevices.length; i < n; i++) {
    String serialNumber = myDevices[i].getSerialNumber();
    if (selectedSerialsSet.contains(serialNumber)) {
      if (!cleared) {
        selectionModel.clearSelection();
        cleared = true;
      }
      selectionModel.addSelectionInterval(i, i);
    }
  }
}
 
Example #11
Source File: LogReader.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
/**
 * Get a reference to the name of the process with the given ID. The
 * reference may contain a null-object, couldn't be retrieved, but may be
 * available later.
 *
 * @param device Device, where the process runs.
 * @param pid ID of the process.
 * @return A reference to a string containing the process name or
 * {@code null}, if the process couldn't be retrieved yet.
 */
private String[] getProcessName(IDevice device, int pid) {
    Map<Integer, String[]> cache = processNameCache.get(device.getSerialNumber());
    if (cache == null) {
        cache = new HashMap<>();
        processNameCache.put(device.getSerialNumber(), cache);
    }

    String[] nameref = cache.get(pid);
    if (nameref == null) {
        nameref = new String[1];
        cache.put(pid, nameref);
    }

    if (nameref[0] == null) {
        for (Client client : device.getClients()) {
            ClientData data = client.getClientData();

            if (data.getPid() == pid) {
                nameref[0] = data.getClientDescription();
            }
        }
    }

    return nameref;
}
 
Example #12
Source File: DefaultDeviceConnection.java    From CXTouch with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Remove device channel, the message and image channel will be rebuilt if other device channels are available.
 * Return a flag indicates whether there are some device channels available after removed.
 *
 * @return true: there are some device channels available, false: there is no device channel available.
 */
public boolean removeDeviceChannel(IDevice device) {
    boolean wirelessMode = AdbUtil.isWirelessDevice(device);
    if (wirelessMode) {
        logger.info("The wireless device channel is removed: {}", getId());
        this.wirelessDevice = null;
        if (usbDevice != null) {
            refreshDeviceChannel(usbDevice);
            return true;
        } else {
            return false;
        }
    } else {
        logger.info("The usb device channel is removed: {}", getId());
        this.usbDevice = null;
        return wirelessDevice != null;
    }

}
 
Example #13
Source File: ControllerInfrastructureService.java    From CXTouch with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void stopWirelessChannel(IDevice device) {
    String deviceId = AdbUtil.getDeviceId(device);
    final IDeviceConnection connection = application.getDeviceConnection(deviceId);
    if (connection == null) {
        throw new IllegalArgumentException("The device doesn't exist: " + deviceId);
    }

    if (!connection.isWirelessMode()) {
        return;
    }
    try {
        CXAdbHelper.disconnect(connection.getIp(), 5555);
    } catch (Exception e) {
        throw new RuntimeException("Executing disconnect failed: " + e.getMessage(), e);
    }

}
 
Example #14
Source File: ServiceEvent.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
public Object onEventReceived(IDevice device) {
	//just start the onCreate for now; we do not care whether the bundle is null
	String shellCmd = String.format("am startservice %s/%s", packageName, servicePath);		
	try {			
		device.executeShellCommand(shellCmd, new GenericReceiver(), 10000, TimeUnit.MILLISECONDS);
		LoggerHelper.logEvent(MyLevel.ADB_EVENT, adbEventFormat(toString(), shellCmd));
	} catch (Exception e) {
		e.printStackTrace();
	}		
	return null;
}
 
Example #15
Source File: OnClickEvent.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
public Object onEventReceived(IDevice device) {		
	String shellCmd = String.format("am startservice --es \"className\" \"%s\""
			+ " --es \"task\" \"onClick\" -n %s/%s", 
			onClickListenerClass, packageName, UtilInstrumenter.COMPONENT_CALLER_SERVICE_HELPER);		
	try {
		device.executeShellCommand(shellCmd, new GenericReceiver(), 10000, TimeUnit.MILLISECONDS);
		LoggerHelper.logEvent(MyLevel.ADB_EVENT, adbEventFormat(toString(), onClickListenerClass));
	} catch (Exception e) {
		e.printStackTrace();
	}		
	return null;
}
 
Example #16
Source File: TestDevice.java    From buck with Apache License 2.0 5 votes vote down vote up
public static TestDevice createRealDevice(String serial) {
  TestDevice device = new TestDevice();
  device.setIsEmulator(false);
  device.setSerialNumber(serial);
  device.setName("device-" + serial);
  device.setState(IDevice.DeviceState.ONLINE);
  return device;
}
 
Example #17
Source File: AndroidService.java    From agent with MIT License 5 votes vote down vote up
public Response setIme(String mobileId, String ime) {
    Device device = DeviceHolder.getConnectedDevice(mobileId);
    if (device == null) {
        return Response.fail(mobileId + "未连接");
    }

    try {
        IDevice iDevice = ((AndroidDevice) device).getIDevice();
        AndroidUtil.setIme(iDevice, ime);
        return Response.success("设置输入法成功");
    } catch (IDeviceExecuteShellCommandException e) {
        log.error("[{}]设置输入法失败", device.getId(), e);
        return Response.fail(e.getMessage());
    }
}
 
Example #18
Source File: InstrumentationTestRunnerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncExopackageDir() throws Exception {
  final Set<String> pushedFilePaths = new HashSet<>();
  IDevice device =
      new TestDevice() {
        @Override
        public void pushFile(String local, String remote) {
          pushedFilePaths.add(remote);
        }
      };
  Path rootFolder = tmp.newFolder("dummy_exo_contents");
  // Set up the files to be written, including the metadata file which specifies the base
  // directory
  Files.write(
      rootFolder.resolve("metadata.txt"), "/data/local/tmp/exopackage/com.example".getBytes());
  Path contents = rootFolder.resolve(Paths.get("a", "b", "c"));
  Files.createDirectories(contents);
  Files.write(contents.resolve("foo"), "Hello World".getBytes());

  // Perform the sync
  InstrumentationTestRunner.syncExopackageDir(rootFolder, device);

  // Now verify the results
  Set<String> expectedPaths =
      ImmutableSet.of(
          "/data/local/tmp/exopackage/com.example/metadata.txt",
          "/data/local/tmp/exopackage/com.example/a/b/c/foo");
  Assert.assertEquals(expectedPaths, pushedFilePaths);
}
 
Example #19
Source File: AdbWifiConnect.java    From ADBWIFI with Apache License 2.0 5 votes vote down vote up
private static DeviceResult getDevice(Project project) {
    List<AndroidFacet> facets = getApplicationFacets(project);
    if (!facets.isEmpty()) {
        AndroidFacet facet = facets.get(0);
        String packageName = AdbUtil.computePackageName(facet);
        AndroidDebugBridge bridge = AndroidSdkUtils.getDebugBridge(project);
        if (bridge == null) {
            error("No platform configured");
            return null;
        }
        int count = 0;
        while (!bridge.isConnected() || !bridge.hasInitialDeviceList()) {
            try {
                Thread.sleep(100);
                count++;
            } catch (InterruptedException e) {
                // pass
            }

            // let's not wait > 10 sec.
            if (count > 100) {
                error("Timeout getting device list!");
                return null;
            }
        }

        IDevice[] devices = bridge.getDevices();
        if (devices.length == 1) {
            return new DeviceResult(devices, facet, packageName);
        } else if (devices.length > 1) {
            return askUserForDevice(facet, packageName);
        } else {
            return null;
        }

    }
    error("No devices found");
    return null;
}
 
Example #20
Source File: DeviceChooserDialog.java    From ADB-Duang with MIT License 5 votes vote down vote up
@NotNull
public static String toString(@NotNull IDevice[] devices) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0, n = devices.length; i < n; i++) {
        builder.append(devices[i].getSerialNumber());
        if (i < n - 1) {
            builder.append(' ');
        }
    }
    return builder.toString();
}
 
Example #21
Source File: UninstallAppEvent.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
public Object onEventReceived(IDevice device) {
	try {
		device.uninstallPackage(packageName);
	} catch (InstallException e) {
		LoggerHelper.logEvent(MyLevel.EXCEPTION_ANALYSIS, e.getMessage());
		e.printStackTrace();
		System.exit(-1);
	}
	return null;
}
 
Example #22
Source File: ScreenView.java    From HJMirror with MIT License 5 votes vote down vote up
ScreenView(HJView parent, IDevice device, int port, int adbPort, int width, int height, float density, String apkPath) {
    super(parent, device);
    this.device = device;
    this.width = width;
    this.height = height;
    this.density = density;
    this.apkPath = apkPath;
    this.port = port;
    this.adbPort = adbPort;
    this.queue = new EventQueue(density);
}
 
Example #23
Source File: MonkeyTestDevice.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
public MonkeyTestDevice(IDevice device) {
    if (device == null) {
        throw new IllegalArgumentException(
                "MonkeyTestDevice(IDevice device), device should not be null.");
    }
    mDevice = device;
    String serialno = device.getSerialNumber();
    if (serialno == null || serialno.isEmpty() || serialno.contains("?")) {
        throw new IllegalArgumentException(
                "MonkeyTestDevice(IDevice device), device should not have a illegal serial number, like null, empty or ??????");
    }
    mSerialNumber = serialno;
}
 
Example #24
Source File: PhoneRestartEvent.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
@Override
public Object onEventReceived(IDevice device) {
	try {
		device.reboot(null);
		LoggerHelper.logEvent(MyLevel.RESTART, "App restarted event sent");
	} catch (Exception e) {
		LoggerHelper.logEvent(MyLevel.EXCEPTION_ANALYSIS, "Not able to reboot device...: " + e.getMessage());
		e.printStackTrace();
	}
	return null;
}
 
Example #25
Source File: PropertyHelper.java    From ADB-Duang with MIT License 5 votes vote down vote up
public static void setDebugLayoutEnabled(IDevice device, boolean enabled, IShellOutputReceiver iShellOutputReceiver) {
    String cmd = "setprop " + Property.DEBUG_LAYOUT_PROPERTY + " " + (enabled ? "true" : "false");
    System.out.println(cmd);
    executeShell(device, iShellOutputReceiver, cmd);
    executeShell(device, null, "am broadcast -a red.dim.updatesystemprop -n red.dim.duang/.UpdateReceiver");

}
 
Example #26
Source File: BlazeAndroidOpenProfilerWindowTask.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public LaunchResult run(
    Executor executor, IDevice device, LaunchStatus launchStatus, ConsolePrinter printer) {
  ApplicationManager.getApplication()
      .invokeLater(() -> AndroidProfilerProgramRunner.createProfilerToolWindow(project, null));
  return LaunchResult.success();
}
 
Example #27
Source File: LogSourcePanel.java    From logviewer with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the combo box with the given list of sources and selected item
 */
void updateDeviceCombo(java.util.List<LogSource> logSourceList, LogSource selection) {
    myIgnoreActionEvents = true;
    mySourceCombo.removeAllItems();
    if (logSourceList != null) {
        for (LogSource source : logSourceList) {
            IDevice device = source.getSource();
            mySourceCombo.addItem(device);
        }
        if (selection != null && selection.getSource() != null) {
            mySourceCombo.setSelectedItem(selection.getSource());
        }
    }
    myIgnoreActionEvents = false;
}
 
Example #28
Source File: LogSourcePanel.java    From logviewer with Apache License 2.0 5 votes vote down vote up
static void renderDeviceName(@NotNull IDevice d, @NotNull ColoredTextContainer component) {
    //component.setIcon(d.isEmulator() ? AndroidIcons.Ddms.Emulator2 : AndroidIcons.Ddms.RealDevice);
    String name;
    if (d.isEmulator()) {
        String avdName = d.getAvdName();
        if (avdName == null) {
            avdName = "unknown";
        }

        name = String.format(" %1$s %2$s ", "Emulator", avdName);
    } else {
        name = String.format(" %1$s ", DevicePropertyUtil.getModel(d, ""));
    }

    component.append(d.getSerialNumber(), SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES);
    component.append(name, SimpleTextAttributes.REGULAR_ATTRIBUTES);

    IDevice.DeviceState deviceState = d.getState();
    if (deviceState != IDevice.DeviceState.ONLINE) {
        String state = String.format("[%1$s] ", d.getState());
        component.append(state, SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES);
    }


    if (deviceState != IDevice.DeviceState.DISCONNECTED && deviceState != IDevice.DeviceState.OFFLINE) {
        component.append(DevicePropertyUtil.getBuild(d), SimpleTextAttributes.GRAY_ATTRIBUTES);
    }

}
 
Example #29
Source File: DeviceConnectHelper.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
public IDevice getConnecedDevice(final String serialNumber) {
    for (IDevice device : AndroidDebugBridge.getBridge().getDevices()) {
        if (serialNumber.equals(device.getSerialNumber())
                && device.getState() == DeviceState.ONLINE) {
            return device;
        }
    }
    return null;
}
 
Example #30
Source File: MonkeyTestDevice.java    From Android-Monkey-Adapter with Apache License 2.0 5 votes vote down vote up
public boolean connect() {
    boolean result = false;
    for (IDevice device : AndroidDebugBridge.getBridge().getDevices()) {
        if (mDevice.getSerialNumber().equals(device.getSerialNumber())
                && mDevice.getState() == DeviceState.ONLINE) {
            mDevice = device;
            result = true;
            break;
        }
    }
    return result;
}