private static void doInitializeDdmlib(@NotNull String adbPath) { synchronized (myDdmsLock) { if (!myDdmLibInitialized) { myDdmLibInitialized = true; DdmPreferences.setLogLevel(Log.LogLevel.INFO.getStringValue()); DdmPreferences.setTimeOut(AndroidUtils.TIMEOUT); AndroidDebugBridge.init(AndroidEnableAdbServiceAction.isAdbServiceEnabled()); LOG.info("DDMLib initialized"); final AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(adbPath, true); waitUntilConnect(bridge); if (!bridge.isConnected()) { LOG.info("Failed to connect debug bridge"); } } else { final AndroidDebugBridge bridge = AndroidDebugBridge.getBridge(); final boolean forceRestart = myAdbCrashed || (bridge != null && !bridge.isConnected()); if (forceRestart) { LOG.info("Restart debug bridge: " + (myAdbCrashed ? "crashed" : "disconnected")); } final AndroidDebugBridge newBridge = AndroidDebugBridge.createBridge(adbPath, forceRestart); waitUntilConnect(newBridge); if (!newBridge.isConnected()) { LOG.info("Failed to connect debug bridge after restart"); } } } }
public AdbBackend() { // [try to] ensure ADB is running String adbLocation = findAdb(); AndroidDebugBridge.init(false /* debugger support */); bridge = AndroidDebugBridge.createBridge(adbLocation, true /* forceNewBridge */); }
public static void terminateDdmlib() { synchronized (myDdmsLock) { AndroidDebugBridge.disconnectBridge(); AndroidDebugBridge.terminate(); LOG.info("DDMLib terminated"); myDdmLibInitialized = false; } }
@Override public void dispose() { if (myBridge != null) { AndroidDebugBridge.removeDeviceChangeListener(this); AndroidDebugBridge.removeDebugBridgeChangeListener(this); myBridge = null; } }
/** * Detects if emulator is running using adb. * * @param serialNo * @return true if running, false otherwise. */ public boolean adbIsRunning(String serialNo) { AndroidDebugBridge adb = mTestManager.getAndroidDebugBridge(); for (IDevice device : adb.getDevices()) { if (device.getSerialNumber().endsWith(serialNo)) { return true; } } return false; }
/** * Initialize the Android Debug Bridge and wait for it to start. Does not reinitialize it if it * has already been initialized (that would through and IllegalStateException...). Synchronized * sine the init call in the library is also synchronized .. just in case. * * @return */ protected AndroidDebugBridge initAndroidDebugBridge() throws MojoExecutionException { synchronized (ADB_LOCK) { if (!adbInitialized) { AndroidDebugBridge.init(false); adbInitialized = true; } AndroidDebugBridge androidDebugBridge = AndroidDebugBridge.createBridge(getAndroidSdk().getAdbPath(), false); waitUntilConnected(androidDebugBridge); return androidDebugBridge; } }
public boolean stop(String serialNo) { // NOPMD /* check adb connection */ if (!mTestManager.isAdbConnected()) { throw new IllegalStateException("ADB is not connected"); } if (!isRunning(serialNo)) { mLog.v("Emualtor \"%s\" is not running. Nothing to stop.", serialNo); return true; } /* verify serial represents emulator, and not a real device */ AndroidDebugBridge adb = mTestManager.getAndroidDebugBridge(); boolean skipAdbStop = true; for (IDevice curDevice : adb.getDevices()) { if (curDevice.getSerialNumber().endsWith(serialNo)) { if (!curDevice.isEmulator()) { throw new IllegalArgumentException("Not an emulator: " + serialNo); } skipAdbStop = false; break; } } if (!skipAdbStop) { // NOPMD /* Killing emulator using adb's embedded control over emulator console */ mLog.v("Killing emulator \"%s\" using adb.", serialNo); if (adbStop(serialNo)) { if (waitForEmualtorStopped(serialNo, DEFAULT_TIMEOUT)) { mLog.v("Emulator \"%s\" is no longer running.", serialNo); return true; } } else { mLog.v("Failed to stop emulator \"%s\" using avd.", serialNo); } } else { mLog.w("Emulator \"%s\" is not visible from adb.", serialNo); } /* Let's kill emulator using emulator console */ mLog.v("Killing emulator \"%s\" using emulator console.", serialNo); if (mConsole.consoleStop(serialNo)) { if (waitForEmualtorStopped(serialNo, DEFAULT_TIMEOUT)) { mLog.v("Emulator \"%s\" is no longer running.", serialNo); return true; } } else { mLog.v("Failed to stop emulator \"%s\" using emulator console.", serialNo); } mLog.e(null, "I really tried to kill \"%s\" emulator. But failed.", serialNo); return false; }
/** * Start the Android Emulator with the specified options. * * @throws org.apache.maven.plugin.MojoExecutionException * @see #emulatorAvd * @see #emulatorWait * @see #emulatorOptions */ protected void startAndroidEmulator() throws MojoExecutionException { parseParameters(); CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); try { String filename; if (isWindows()) { filename = writeEmulatorStartScriptWindows(); } else { filename = writeEmulatorStartScriptUnix(); } final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge(); if (androidDebugBridge.isConnected()) { List<IDevice> devices = Arrays.asList(androidDebugBridge.getDevices()); int numberOfDevices = devices.size(); getLog() .info("Found " + numberOfDevices + " devices connected with the Android Debug Bridge"); IDevice existingEmulator = null; for (IDevice device : devices) { if (device.isEmulator()) { if (isExistingEmulator(device)) { existingEmulator = device; break; } } } if (existingEmulator == null) { getLog().info(START_EMULATOR_MSG + filename); executor.executeCommand(filename, null); getLog().info(START_EMULATOR_WAIT_MSG + parsedWait); // wait for the emulator to start up Thread.sleep(new Long(parsedWait)); } else { getLog() .info( String.format( "Emulator already running [Serial No: '%s', AVD Name '%s']. Skipping start and wait.", existingEmulator.getSerialNumber(), existingEmulator.getAvdName())); } } } catch (Exception e) { throw new MojoExecutionException("", e); } }
public DevicePanel(@NotNull Project project, @NotNull DeviceContext context) { myProject = project; myDeviceContext = context; Disposer.register(myProject, this); AndroidDebugBridge.addDeviceChangeListener(this); AndroidDebugBridge.addDebugBridgeChangeListener(this); ClientData.setMethodProfilingHandler(new OpenVmTraceHandler(project)); ClientData.setHprofDumpHandler(new SaveHprofHandler(project)); ClientData.setAllocationTrackingHandler(new ShowAllocationsHandler(project)); initializeDeviceCombo(); initializeClientsList(); }
@Override public void close() { LOGGER.debug("close() - start"); if (injector != null) injector.close(); if (device != null) { synchronized (device) { if (hasFilledAdbPath()) AndroidDebugBridge.disconnectBridge(); AndroidDebugBridge.terminate(); } } LOGGER.debug("close() - end"); }
/** * Performs the callback action on the devices determined by {@link * #shouldDoWithThisDevice(com.android.ddmlib.IDevice)} * * @param deviceCallback the action to perform on each device * @throws org.apache.maven.plugin.MojoExecutionException in case there is a problem * @throws org.apache.maven.plugin.MojoFailureException in case there is a problem */ protected void doWithDevices(final DeviceCallback deviceCallback) throws MojoExecutionException, MojoFailureException { final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge(); if (!androidDebugBridge.isConnected()) { throw new MojoExecutionException("Android Debug Bridge is not connected."); } waitForInitialDeviceList(androidDebugBridge); List<IDevice> devices = Arrays.asList(androidDebugBridge.getDevices()); int numberOfDevices = devices.size(); getLog().info("Found " + numberOfDevices + " devices connected with the Android Debug Bridge"); if (devices.size() == 0) { throw new MojoExecutionException("No online devices attached."); } boolean shouldRunOnAllDevices = StringUtils.isBlank(device); if (shouldRunOnAllDevices) { getLog().info("android.device parameter not set, using all attached devices"); } else { getLog().info("android.device parameter set to " + device); } ArrayList<DoThread> doThreads = new ArrayList<DoThread>(); for (final IDevice idevice : devices) { if (shouldRunOnAllDevices) { String deviceType = idevice.isEmulator() ? "Emulator " : "Device "; getLog().info(deviceType + DeviceHelper.getDescriptiveName(idevice) + " found."); } if (shouldRunOnAllDevices || shouldDoWithThisDevice(idevice)) { DoThread deviceDoThread = new DoThread() { public void runDo() throws MojoFailureException, MojoExecutionException { deviceCallback.doWithDevice(idevice); } }; doThreads.add(deviceDoThread); deviceDoThread.start(); } } joinAllThreads(doThreads); throwAnyDoThreadErrors(doThreads); if (!shouldRunOnAllDevices && doThreads.isEmpty()) { throw new MojoExecutionException("No device found for android.device=" + device); } }
@Nullable public AndroidDebugBridge getDebugBridge(@NotNull Project project) { if (!initializeDdmlib(project)) { return null; } return AndroidDebugBridge.getBridge(); }
@Override public void shutdown() { for (IMonkeyDevice device : devices) { device.dispose(); } AndroidDebugBridge.terminate(); }
/** * Stop the running Android Emulators. * * @throws org.apache.maven.plugin.MojoExecutionException */ protected void stopAndroidEmulators() throws MojoExecutionException { final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge(); if (androidDebugBridge.isConnected()) { List<IDevice> devices = Arrays.asList(androidDebugBridge.getDevices()); int numberOfDevices = devices.size(); getLog() .info("Found " + numberOfDevices + " devices connected with the Android Debug Bridge"); for (IDevice device : devices) { if (device.isEmulator()) { stopEmulator(device); } else { getLog() .info("Skipping stop. Not an emulator. " + DeviceHelper.getDescriptiveName(device)); } } } }
/** * Wait for the Android Debug Bridge to return an initial device list. * * @param androidDebugBridge * @throws MojoExecutionException */ protected void waitForInitialDeviceList(final AndroidDebugBridge androidDebugBridge) throws MojoExecutionException { if (!androidDebugBridge.hasInitialDeviceList()) { getLog().info("Waiting for initial device list from the Android Debug Bridge"); long limitTime = System.currentTimeMillis() + ADB_TIMEOUT_MS; while (!androidDebugBridge.hasInitialDeviceList() && (System.currentTimeMillis() < limitTime)) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new MojoExecutionException( "Interrupted waiting for initial device list from Android Debug Bridge"); } } if (!androidDebugBridge.hasInitialDeviceList()) { getLog().error("Did not receive initial device list from the Android Debug Bridge."); } } }
/** * Checks the attached devices looking for one whose device id matches the specified regex. * * @param deviceIdRegex the regular expression to match against * @return the Device (if found), or null (if not found). */ private IDevice findAttacedDevice(String deviceIdRegex) { Pattern pattern = Pattern.compile(deviceIdRegex); for (IDevice device : bridge.getDevices()) { String serialNumber = device.getSerialNumber(); if (pattern.matcher(serialNumber).matches()) { return device; } } return null; }
private static void waitUntilConnect(@NotNull AndroidDebugBridge bridge) { while (!bridge.isConnected() && !Thread.currentThread().isInterrupted()) { try { //noinspection BusyWait Thread.sleep(1000); } catch (InterruptedException e) { LOG.debug(e); return; } } }
@NotNull private IDevice[] getFilteredDevices(AndroidDebugBridge bridge) { final List<IDevice> filteredDevices = new ArrayList<IDevice>(); for (IDevice device : bridge.getDevices()) { if (myFilter == null || myFilter.value(device)) { filteredDevices.add(device); } } // Do not filter launching cloud devices as they are just unselectable progress markers // that are replaced with the actual cloud devices as soon as they are up and the actual cloud // devices will be filtered above. return filteredDevices.toArray(new IDevice[filteredDevices.size()]); }
/** * Initialize the system object. <br> * Get all the connected devices (if exist), set port forwarding & initialize the TCP connection * <br> */ private AdbController() throws Exception { adbLocation = findAdbFile(); // Init the AndroidDebugBridge object try { AndroidDebugBridge.init(false); } catch (Exception e) { if (e.getMessage() .contains("AndroidDebugBridge.init() has already been called.")) {; // ignore } else { throw e; } } adb = AndroidDebugBridge.createBridge( adbLocation.getAbsolutePath() + File.separator + "adb", true); if (adb == null) { throw new IllegalStateException("Failed to create ADB bridge"); } AndroidDebugBridge.addDeviceChangeListener(this); }
private void setBridge(@Nullable AndroidDebugBridge bridge) { myBridge = bridge; myComboBoxModel.removeAllElements(); IDevice[] devices = myBridge == null ? null : myBridge.getDevices(); if (devices == null || devices.length == 0) { myComboBoxModel.addElement(NO_DEVICES); } else { for (IDevice device : devices) { myComboBoxModel.addElement(device); } } myDevicesComboBox.setSelectedIndex(0); }
/** * Run a wait loop until adb is connected or trials run out. This method seems to work more * reliably then using a listener. * * @param adb */ private void waitUntilConnected(AndroidDebugBridge adb) { int trials = 10; final int connectionWaitTime = 50; while (trials > 0) { try { Thread.sleep(connectionWaitTime); } catch (InterruptedException e) { e.printStackTrace(); } if (adb.isConnected()) { break; } trials--; } }
/** * Install and execute the tests on all specified devices. * * @return {@code true} if there were no test failures or exceptions thrown. */ public boolean run() { checkArgument(applicationApk.exists(), "Could not find application APK."); checkArgument(instrumentationApk.exists(), "Could not find instrumentation APK."); AndroidDebugBridge adb = SpoonUtils.initAdb(androidSdk); try { // If we were given an empty serial set, load all available devices. Set<String> serials = this.serials; if (serials.isEmpty()) { serials = SpoonUtils.findAllDevices(adb); } // Execute all the things... SpoonSummary summary = runTests(adb, serials); // ...and render to HTML new HtmlRenderer(summary, SpoonUtils.GSON, output).render(); return parseOverallSuccess(summary); } finally { AndroidDebugBridge.terminate(); } }
/** {@inheritDoc} */ public IDevice[] getDevices() { if (mAdbBridge == null) { throw new IllegalStateException("getDevices called before init"); } return mAdbBridge.getDevices(); }
/** {@inheritDoc} */ public void addDeviceChangeListener(IDeviceChangeListener listener) { AndroidDebugBridge.addDeviceChangeListener(listener); }
/** {@inheritDoc} */ public void removeDeviceChangeListener(IDeviceChangeListener listener) { AndroidDebugBridge.removeDeviceChangeListener(listener); }
/** {@inheritDoc} */ public void init(boolean clientSupport, String adbOsLocation) { AndroidDebugBridge.init(clientSupport); mAdbBridge = AndroidDebugBridge.createBridge(adbOsLocation, false); }
public void terminate() { AndroidDebugBridge.terminate(); }
/** {@inheritDoc} */ public void disconnectBridge() { AndroidDebugBridge.disconnectBridge(); }
/** * Performs the callback action on the devices determined by {@link * #shouldDoWithThisDevice(com.android.ddmlib.IDevice)} * * @param deviceCallback the action to perform on each device * @throws org.apache.maven.plugin.MojoExecutionException in case there is a problem * @throws org.apache.maven.plugin.MojoFailureException in case there is a problem */ protected void doWithDevices(final DeviceCallback deviceCallback) throws MojoExecutionException, MojoFailureException { final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge(); if (!androidDebugBridge.isConnected()) { throw new MojoExecutionException("Android Debug Bridge is not connected."); } waitForInitialDeviceList(androidDebugBridge); List<IDevice> devices = Arrays.asList(androidDebugBridge.getDevices()); int numberOfDevices = devices.size(); getLog().debug("Found " + numberOfDevices + " devices connected with the Android Debug Bridge"); if (devices.size() == 0) { throw new MojoExecutionException("No online devices attached."); } int threadCount = getDeviceThreads(); if (getDeviceThreads() == 0) { getLog() .info( "android.devicesThreads parameter not set, using a thread for each attached device"); threadCount = numberOfDevices; } else { getLog().info("android.devicesThreads parameter set to " + getDeviceThreads()); } boolean shouldRunOnAllDevices = getDevices().size() == 0; if (shouldRunOnAllDevices) { getLog().info("android.devices parameter not set, using all attached devices"); } else { getLog().info("android.devices parameter set to " + getDevices().toString()); } ArrayList<DoThread> doThreads = new ArrayList<DoThread>(); ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (final IDevice idevice : devices) { if (shouldRunOnAllDevices) { String deviceType = idevice.isEmulator() ? "Emulator " : "Device "; getLog().info(deviceType + DeviceHelper.getDescriptiveName(idevice) + " found."); } if (shouldRunOnAllDevices || shouldDoWithThisDevice(idevice)) { DoThread deviceDoThread = new DoThread() { public void runDo() throws MojoFailureException, MojoExecutionException { deviceCallback.doWithDevice(idevice); } }; doThreads.add(deviceDoThread); executor.execute(deviceDoThread); } } executor.shutdown(); while (!executor.isTerminated()) { // waiting for threads finish } throwAnyDoThreadErrors(doThreads); if (!shouldRunOnAllDevices && doThreads.isEmpty()) { throw new MojoExecutionException( "No device found for android.device=" + getDevices().toString()); } }
public void createAndroidVirtualDeviceAvailable( @Observes AndroidVirtualDeviceEvent event, AndroidBridge bridge, AndroidExtensionConfiguration configuration, AndroidSdk sdk, ProcessExecutor executor) throws AndroidExecutionException { if (!bridge.isConnected()) { throw new IllegalStateException( "Android debug bridge must be connected in order to spawn emulator"); } String name = configuration.getAvdName(); AndroidDevice running = null; for (AndroidDevice device : bridge.getDevices()) { if (equalsIgnoreNulls(name, device.getAvdName())) { running = device; break; } } if (running == null) { CountDownWatch countdown = new CountDownWatch(configuration.getEmulatorBootupTimeoutInSeconds(), TimeUnit.SECONDS); log.log( Level.INFO, "Waiting {0} seconds for emulator {1} to be started and connected.", new Object[] {countdown.timeout(), name}); // discover what device was added here DeviceConnectDiscovery deviceDiscovery = new DeviceConnectDiscovery(); AndroidDebugBridge.addDeviceChangeListener(deviceDiscovery); Process emulator = startEmulator(executor, sdk, name, configuration.getEmulatorOptions()); androidEmulator.set(new AndroidEmulator(emulator)); log.log( Level.FINE, "Emulator process started, {0} seconds remaining to start the device {1}", new Object[] {countdown.timeLeft(), name}); waitUntilBootUpIsComplete(deviceDiscovery, executor, sdk, countdown); running = deviceDiscovery.getDiscoveredDevice(); AndroidDebugBridge.removeDeviceChangeListener(deviceDiscovery); } else { log.info( "Emulator for device " + name + " is already started, device serial is " + running.getSerialNumber() + ". Emulator will not be reinitialized."); } // fire event that we have a device ready androidDevice.set(running); androidDeviceReady.fire(new AndroidDeviceReady(running)); }