com.android.ddmlib.IDevice

Here are the examples of the java api com.android.ddmlib.IDevice taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

147 Examples 7

19 Source : DeviceChooserDialog.java
with Apache License 2.0
from typ0520

private void updateOkButton() {
    IDevice[] devices = getSelectedDevices();
    boolean enabled = devices.length > 0;
    for (IDevice device : devices) {
        if (!device.isOnline()) {
            enabled = false;
        }
    }
    getOKAction().setEnabled(enabled);
}

19 Source : ServiceCommunicator.java
with Apache License 2.0
from typ0520

public <T> T talkToService(IDevice device, Communicator<T> communicator) throws IOException {
    try {
        device.createForward(mLocalPort, mPackageName, IDevice.DeviceUnixSocketNamespace.ABSTRACT);
    } catch (TimeoutException e) {
        throw new IOException(e);
    } catch (AdbCommandRejectedException e2) {
        throw new IOException(e2);
    }
    try {
        return talkToServiceWithinPortForward(communicator, mLocalPort);
    } finally {
        try {
            device.removeForward(mLocalPort, mPackageName, IDevice.DeviceUnixSocketNamespace.ABSTRACT);
        } catch (IOException | TimeoutException | AdbCommandRejectedException e) {
            // we don't worry that much about failures while removing port forwarding
            mLogger.warning("Exception while removing port forward: " + e);
        }
    }
}

19 Source : LogCatReceiverTask.java
with GNU General Public License v3.0
from tranleduy2000

public clreplaced LogCatReceiverTask implements Runnable {

    // $NON-NLS-1$
    private static final String LOGCAT_COMMAND = "logcat -v long";

    private static final int DEVICE_POLL_INTERVAL_MSEC = 1000;

    private static final LogCatMessage sDeviceDisconnectedMsg = errorMessage("Device disconnected: 1");

    private static final LogCatMessage sConnectionTimeoutMsg = errorMessage("LogCat Connection timed out");

    private static final LogCatMessage sConnectionErrorMsg = errorMessage("LogCat Connection error");

    private final IDevice mDevice;

    private final LogCatOutputReceiver mReceiver;

    private final LogCatMessageParser mParser;

    private final AtomicBoolean mCancelled;

    @GuardedBy("this")
    private final Set<LogCatListener> mListeners = new HashSet<LogCatListener>();

    public LogCatReceiverTask(@NonNull IDevice device) {
        mDevice = device;
        mReceiver = new LogCatOutputReceiver();
        mParser = new LogCatMessageParser();
        mCancelled = new AtomicBoolean();
    }

    @Override
    public void run() {
        // wait while device comes online
        while (!mDevice.isOnline()) {
            try {
                Thread.sleep(DEVICE_POLL_INTERVAL_MSEC);
            } catch (InterruptedException e) {
                return;
            }
        }
        try {
            mDevice.executeShellCommand(LOGCAT_COMMAND, mReceiver, 0);
        } catch (TimeoutException e) {
            notifyListeners(Collections.singletonList(sConnectionTimeoutMsg));
        } catch (AdbCommandRejectedException ignored) {
        // will not be thrown as long as the shell supports logcat
        } catch (ShellCommandUnresponsiveException ignored) {
        // this will not be thrown since the last argument is 0
        } catch (IOException e) {
            notifyListeners(Collections.singletonList(sConnectionErrorMsg));
        }
        notifyListeners(Collections.singletonList(sDeviceDisconnectedMsg));
    }

    public void stop() {
        mCancelled.set(true);
    }

    private clreplaced LogCatOutputReceiver extends MultiLineReceiver {

        public LogCatOutputReceiver() {
            setTrimLine(false);
        }

        /**
         * Implements {@link IShellOutputReceiver#isCancelled() }.
         */
        @Override
        public boolean isCancelled() {
            return mCancelled.get();
        }

        @Override
        public void processNewLines(String[] lines) {
            if (!mCancelled.get()) {
                processLogLines(lines);
            }
        }

        private void processLogLines(String[] lines) {
            List<LogCatMessage> newMessages = mParser.processLogLines(lines, mDevice);
            if (!newMessages.isEmpty()) {
                notifyListeners(newMessages);
            }
        }
    }

    public synchronized void addLogCatListener(LogCatListener l) {
        mListeners.add(l);
    }

    public synchronized void removeLogCatListener(LogCatListener l) {
        mListeners.remove(l);
    }

    private synchronized void notifyListeners(List<LogCatMessage> messages) {
        for (LogCatListener l : mListeners) {
            l.log(messages);
        }
    }

    private static LogCatMessage errorMessage(String msg) {
        return new LogCatMessage(LogLevel.ERROR, "", "", "", "", "", msg);
    }
}

19 Source : ADB.java
with Apache License 2.0
from TMLAndroid

// 获取连接的设备列表
public IDevice[] getDevices() {
    IDevice[] devicelist = null;
    if (mAndroidDebugBridge != null) {
        devicelist = mAndroidDebugBridge.getDevices();
    }
    return devicelist;
}

19 Source : MobileChangeHandler.java
with MIT License
from opendx

protected void mobileConnected(IDevice iDevice) {
    String mobileId = iDevice.getSerialNumber();
    Device device = DeviceHolder.get(mobileId);
    if (device == null) {
        log.info("[{}]首次接入agent", mobileId);
        Mobile mobile = ServerClient.getInstance().getMobileById(mobileId);
        log.info("[{}]启动appium server...", mobileId);
        AppiumServer appiumServer = new AppiumServer();
        appiumServer.start();
        log.info("[{}]启动appium server完成, url: {}", mobileId, appiumServer.getUrl());
        if (mobile == null) {
            try {
                log.info("[{}]首次接入server,开始初始化...", mobileId);
                device = initMobile(iDevice, appiumServer);
            } catch (Exception e) {
                log.info("[{}]停止appium server", mobileId);
                appiumServer.stop();
                throw new RuntimeException(String.format("[%s]初始化失败", mobileId), e);
            }
        } else {
            log.info("[{}]已接入过server", mobileId);
            device = newMobile(iDevice, mobile, appiumServer);
        }
        beforePutDeviceToHolder(device);
        DeviceHolder.put(mobileId, device);
    } else {
        log.info("[{}]重新接入agent", mobileId);
        reconnectToAgent(device, iDevice);
    }
    device.onlineToServer();
    log.info("[{}]MobileConnected处理完成", mobileId);
}

19 Source : MobileChangeHandler.java
with MIT License
from opendx

protected void reconnectToAgent(Device device, IDevice iDevice) {
}

19 Source : DefaultIosDeviceChangeListener.java
with MIT License
from opendx

@Override
protected MobileDevice newMobile(IDevice iDevice, Mobile mobile, AppiumServer appiumServer) {
    return new IosDevice(mobile, appiumServer);
}

19 Source : DefaultIosDeviceChangeListener.java
with MIT License
from opendx

@Override
public void deviceConnected(IDevice iDevice) {
    new Thread(() -> mobileConnected(iDevice)).start();
}

19 Source : DefaultIosDeviceChangeListener.java
with MIT License
from opendx

@Override
public void deviceDisconnected(IDevice iDevice) {
    new Thread(() -> mobileDisconnected(iDevice.getSerialNumber())).start();
}

19 Source : Minitouch.java
with MIT License
from opendx

/**
 * Created by jiangyitao.
 */
@Slf4j
public clreplaced Minitouch {

    public static final String LOCAL_MINITOUCH_PATH = "vendor/minitouch/%s/minitouch";

    public static final String REMOTE_MINITOUCH_PATH = AndroidDevice.TMP_FOLDER + "/minitouch";

    private IDevice iDevice;

    private String mobileId;

    /**
     * https://github.com/openstf/minitouch#-max-contacts-max-x-max-y-max-pressure
     */
    private int width;

    /**
     * https://github.com/openstf/minitouch#-max-contacts-max-x-max-y-max-pressure
     */
    private int height;

    /**
     * 运行在Mobile里的进程id
     */
    private int pid;

    /**
     * 用于向minitouch发送指令
     */
    private PrintWriter printWriter;

    private boolean isRunning = false;

    public Minitouch(IDevice iDevice) {
        this.iDevice = iDevice;
        mobileId = iDevice.getSerialNumber();
    }

    public void setIDevice(IDevice iDevice) {
        this.iDevice = iDevice;
    }

    /**
     * 开始运行minitouch
     *
     * @throws Exception
     */
    public synchronized void start() throws Exception {
        if (isRunning) {
            return;
        }
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(() -> {
            try {
                log.info("[{}]启动minitouch: {}", mobileId, REMOTE_MINITOUCH_PATH);
                iDevice.executeShellCommand(REMOTE_MINITOUCH_PATH, new MultiLineReceiver() {

                    @Override
                    public void processNewLines(String[] lines) {
                        for (String line : lines) {
                            log.info("[{}]minitouch: {}", mobileId, line);
                            if (!StringUtils.isEmpty(line) && line.startsWith("Type")) {
                                // minitouch启动完成
                                countDownLatch.countDown();
                            }
                        }
                    }

                    @Override
                    public boolean isCancelled() {
                        return false;
                    }
                }, 0, TimeUnit.SECONDS);
                log.info("[{}]minitouch已停止运行", mobileId);
                isRunning = false;
            } catch (Exception e) {
                throw new RuntimeException(String.format("[%s]启动minitouch失败", mobileId), e);
            }
        }).start();
        int minitouchStartTimeoutInSeconds = 30;
        boolean minitouchStartSuccess = countDownLatch.await(minitouchStartTimeoutInSeconds, TimeUnit.SECONDS);
        if (!minitouchStartSuccess) {
            throw new RuntimeException(String.format("[%s]启动minitouch失败,超时时间:%d秒", mobileId, minitouchStartTimeoutInSeconds));
        }
        log.info("[{}]minitouch启动完成", mobileId);
        isRunning = true;
        int localPort = PortProvider.getMinitouchAvailablePort();
        log.info("[{}]adb forward: {} -> remote minitouch", mobileId, localPort);
        iDevice.createForward(localPort, "minitouch", IDevice.DeviceUnixSocketNamespace.ABSTRACT);
        new Thread(() -> {
            try (Socket socket = new Socket("127.0.0.1", localPort);
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter printWriter = new PrintWriter(socket.getOutputStream())) {
                this.printWriter = printWriter;
                String line;
                while ((line = br.readLine()) != null) {
                    // https://github.com/openstf/minitouch#readable-from-the-socket
                    if (line.startsWith("^")) {
                        // ^ <max-contacts> <max-x> <max-y> <max-pressure>
                        // ^ 10 1079 1919 2048
                        String[] content = line.split(" ");
                        width = Integer.parseInt(content[2]);
                        height = Integer.parseInt(content[3]);
                        log.info("[{}]minitouch width: {} height: {}", mobileId, width, height);
                    } else if (line.startsWith("$")) {
                        // $ 12310
                        pid = Integer.parseInt(line.split(" ")[1]);
                        log.info("[{}]minitouch pid: {}", mobileId, pid);
                    }
                }
            } catch (Exception e) {
                log.error("[{}]处理minitouch数据失败", mobileId, e);
            }
            if (printWriter != null) {
                printWriter.close();
            }
            try {
                log.info("[{}]移除adb forward: {} -> remote minitouch", mobileId, localPort);
                iDevice.removeForward(localPort, "minitouch", IDevice.DeviceUnixSocketNamespace.ABSTRACT);
            } catch (Exception e) {
                log.error("[{}]移除adb forward出错", mobileId, e);
            }
        }).start();
    }

    /**
     * 停止运行monitouch
     */
    public synchronized void stop() {
        if (isRunning) {
            String cmd = "kill -9 " + pid;
            try {
                log.info("[{}]kill minitouch: {}", mobileId, cmd);
                iDevice.executeShellCommand(cmd, new NullOutputReceiver());
            } catch (Exception e) {
                log.error("[{}]{}执行出错", mobileId, cmd, e);
            }
        }
    }

    /**
     * 按下 https://github.com/openstf/minitouch#d-contact-x-y-pressure
     *
     * @param x
     * @param y
     */
    public void touchDown(int x, int y, int screenWidth, int screenHeight) {
        int minitouchX = (int) (((float) x) / screenWidth * width);
        int minitouchY = (int) (((float) y) / screenHeight * height);
        commit(String.format("d 0 %d %d 50", minitouchX, minitouchY));
    }

    /**
     * 松手 https://github.com/openstf/minitouch#u-contact
     */
    public void touchUp() {
        commit("u 0");
    }

    /**
     * 滑动 https://github.com/openstf/minitouch#m-contact-x-y-pressure
     */
    public void moveTo(int x, int y, int screenWidth, int screenHeight) {
        int minitouchX = (int) (((float) x) / screenWidth * width);
        int minitouchY = (int) (((float) y) / screenHeight * height);
        commit(String.format("m 0 %d %d 50", minitouchX, minitouchY));
    }

    /**
     * 提交minitouch命令
     *
     * @param cmd
     */
    private void commit(String cmd) {
        if (printWriter != null) {
            printWriter.write(cmd + "\nc\n");
            printWriter.flush();
        }
    }
}

19 Source : Minitouch.java
with MIT License
from opendx

public void setIDevice(IDevice iDevice) {
    this.iDevice = iDevice;
}

19 Source : SelectDeviceAction.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public void deviceDisconnected(IDevice id) {
    resultChanged(null);
}

19 Source : SelectDeviceAction.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public void deviceConnected(IDevice id) {
    resultChanged(null);
}

19 Source : SelectDeviceAction.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public void deviceChanged(IDevice id, int i) {
    resultChanged(null);
}

19 Source : MobileDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

public void deviceConnected(IDevice device) {
}

19 Source : MobileDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

public void deviceChanged(IDevice device, int changeType) {
    if (this.device.equals(device) && (changeType & IDevice.CHANGE_STATE) == IDevice.CHANGE_STATE) {
        this.updateDescription();
        firePropertySetsChange(null, null);
    }
}

19 Source : MobileDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

public void deviceDisconnected(IDevice device) {
}

19 Source : EmulatorDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

/**
 * @author tom
 * @author arsi
 */
public clreplaced EmulatorDeviceNode extends AbstractNode implements AndroidDebugBridge.IDeviceChangeListener {

    private static final Logger LOG = Logger.getLogger(EmulatorDeviceNode.clreplaced.getName());

    private final IDevice device;

    private final EmulatorControlSupport emulatorControl;

    EmulatorDeviceNode(final IDevice device) {
        super(new DeviceChildren(device), Lookups.fixed(device, new EmulatorControlSupport(device), new DevicesNode.MobileDeviceHolder(device, null, device.getSerialNumber())));
        replacedert device != null;
        this.device = device;
        emulatorControl = getLookup().lookup(EmulatorControlSupport.clreplaced);
        this.setDisplayName(device.getSerialNumber());
        this.updateDescription();
        this.setIconBaseWithExtension("org/netbeans/modules/android/project/resources/emulator.png");
        AndroidDebugBridge.addDeviceChangeListener(this);
        this.addNodeListener(new NodeListener() {

            @Override
            public void childrenAdded(NodeMemberEvent event) {
            }

            @Override
            public void childrenRemoved(NodeMemberEvent event) {
            }

            @Override
            public void childrenReordered(NodeReorderEvent event) {
            }

            @Override
            public void nodeDestroyed(NodeEvent event) {
                AndroidDebugBridge.removeDeviceChangeListener(EmulatorDeviceNode.this);
            }

            @Override
            public void propertyChange(PropertyChangeEvent event) {
            }
        });
    }

    private void updateDescription() {
        final String serNum = this.device.getSerialNumber();
        final IDevice.DeviceState state = this.device.getState();
        this.setShortDescription(NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "HINT_Device", serNum, state != null ? state.toString() : "(unknown state)"));
    }

    @Override
    public Action[] getActions(boolean context) {
        List<? extends Action> actionsForPath = Utilities.actionsForPath("Android/ADB/EmulatorDevice");
        return actionsForPath.toArray(new Action[actionsForPath.size()]);
    }

    @Override
    public PropertySet[] getPropertySets() {
        final Sheet.Set defset = Sheet.createPropertiesSet();
        defset.put(new PropertySupport.ReadOnly<String>("PROP_DeviceId", String.clreplaced, NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "PROP_DeviceId"), NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "DESC_DeviceId")) {

            @Override
            public String getValue() throws IllegalAccessException, InvocationTargetException {
                return device.getSerialNumber();
            }
        });
        defset.put(new PropertySupport.ReadOnly<String>("PROP_State", String.clreplaced, NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "PROP_State"), NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "DESC_State")) {

            @Override
            public String getValue() throws IllegalAccessException, InvocationTargetException {
                return device.getState().toString();
            }
        });
        defset.put(new PropertySupport.ReadOnly<Boolean>("PROP_Emulator", Boolean.clreplaced, NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "PROP_Emulator"), NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "DESC_Emulator")) {

            @Override
            public Boolean getValue() throws IllegalAccessException, InvocationTargetException {
                return device.isEmulator();
            }
        });
        addEmulatorControls(defset);
        final Sheet.Set devset = new Sheet.Set();
        devset.setExpert(true);
        devset.setName("SET_DeviceProps");
        devset.setDisplayName(NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "SET_DeviceProps"));
        clreplaced DeviceProperty extends PropertySupport.ReadOnly<String> {

            private final String name;

            private final String value;

            public DeviceProperty(String name, String value) {
                super(name, String.clreplaced, name, name);
                replacedert name != null;
                replacedert value != null;
                this.name = name;
                this.value = value;
            }

            @Override
            public String getValue() throws IllegalAccessException, InvocationTargetException {
                return this.value;
            }
        }
        final Map<String, String> props = device.getProperties();
        for (Map.Entry<String, String> prop : props.entrySet()) {
            devset.put(new DeviceProperty(prop.getKey(), prop.getValue()));
        }
        return new PropertySet[] { defset, devset };
    }

    @Override
    public void deviceConnected(IDevice device) {
    }

    @Override
    public void deviceDisconnected(IDevice device) {
    }

    @Override
    public void deviceChanged(IDevice device, int changeType) {
        if (this.device.equals(device) && (changeType & IDevice.CHANGE_STATE) == IDevice.CHANGE_STATE) {
            this.updateDescription();
            firePropertySetsChange(null, null);
        }
    }

    private void addEmulatorControls(Sheet.Set defset) {
        if (!device.isEmulator()) {
            return;
        }
        for (final EmulatorControlSupport.Control ctrl : EmulatorControlSupport.Control.values()) {
            defset.put(new PropertySupport.ReadWrite<String>(ctrl.name(), String.clreplaced, ctrl.getDisplayName(), ctrl.getDescription()) {

                @Override
                public String getValue() throws IllegalAccessException, InvocationTargetException {
                    return emulatorControl.getData(ctrl);
                }

                @Override
                public void setValue(String val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
                    emulatorControl.setData(ctrl, val);
                }

                @Override
                public PropertyEditor getPropertyEditor() {
                    return PropertyUtils.stringPropertyEditorWithTags(emulatorControl.getTags(ctrl));
                }
            });
        }
    }

    private static clreplaced DeviceChildren extends Children.Keys<ClientHolder> implements AndroidDebugBridge.IDeviceChangeListener {

        private final IDevice device;

        public DeviceChildren(final IDevice device) {
            replacedert device != null;
            this.device = device;
        }

        @Override
        protected void addNotify() {
            AndroidDebugBridge.addDeviceChangeListener(this);
            updateKeys();
        }

        private void updateKeys() {
            Set<ClientHolder> keys = new HashSet<>();
            final Client[] clients = device.getClients();
            for (Client client : clients) {
                keys.add(new ClientHolder(client));
            }
            this.setKeys(keys);
        }

        @Override
        protected void removeNotify() {
            AndroidDebugBridge.removeDeviceChangeListener(this);
            this.setKeys(new ClientHolder[0]);
        }

        @Override
        protected Node[] createNodes(ClientHolder key) {
            replacedert key != null;
            return new Node[] { new ClientNode(key.client) };
        }

        @Override
        public void deviceConnected(IDevice device) {
        // Not important
        }

        @Override
        public void deviceDisconnected(IDevice device) {
        // Not important
        }

        @Override
        public void deviceChanged(IDevice device, int eventType) {
            if (this.device.equals(device) && (eventType & IDevice.CHANGE_CLIENT_LIST) == IDevice.CHANGE_CLIENT_LIST) {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        updateKeys();
                    }
                });
            }
        }
    }

    private static clreplaced ClientHolder {

        public final Client client;

        public ClientHolder(final Client client) {
            replacedert client != null;
            this.client = client;
        }

        @Override
        public String toString() {
            return this.client.getClientData().getClientDescription();
        }

        @Override
        public int hashCode() {
            return this.client.getClientData().getPid();
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof ClientHolder) {
                final ClientHolder other = (ClientHolder) obj;
                return this.client.getClientData().getPid() == other.client.getClientData().getPid();
            }
            return false;
        }
    }

    public static clreplaced ScreenShotAction extends NodeAction {

        private static final String PNG = "png";

        @Override
        protected void performAction(Node[] nodes) {
            replacedert nodes != null;
            replacedert nodes.length == 1;
            final IDevice device = nodes[0].getLookup().lookup(IDevice.clreplaced);
            replacedert device != null;
            try {
                final RawImage image = device.getScreenshot();
                if (image == null) {
                    // NOI18N
                    throw new IOException("No screenshot");
                }
                int imageType;
                // determine image format
                switch(image.bpp) {
                    case 16:
                        {
                            imageType = BufferedImage.TYPE_USHORT_565_RGB;
                            break;
                        }
                    default:
                        {
                            imageType = BufferedImage.TYPE_INT_ARGB;
                            break;
                        }
                }
                final BufferedImage img = new BufferedImage(image.width, image.height, imageType);
                final DataBuffer db = img.getRaster().getDataBuffer();
                for (int y = 0; y < image.height; y++) {
                    for (int x = 0; x < image.width; x++) {
                        int color;
                        switch(imageType) {
                            case BufferedImage.TYPE_USHORT_565_RGB:
                                {
                                    byte l = image.data[2 * (y * image.width + x)];
                                    byte h = image.data[2 * (y * image.width + x) + 1];
                                    color = ((h << 8) | (l & 0xff)) & 0xffff;
                                    break;
                                }
                            default:
                                {
                                    color = image.getARGB((image.bpp / 8) * (y * image.width + x));
                                    break;
                                }
                        }
                        db.setElem(y * image.width + x, color);
                    }
                }
                // NOI18N
                final String tmpVal = System.getProperty("java.io.tmpdir");
                final File tmpFile = FileUtil.normalizeFile(new File(tmpVal));
                final String name = FileUtil.findFreeFileName(FileUtil.toFileObject(tmpFile), device.getSerialNumber(), PNG);
                final File pictureFile = new File(tmpFile, name + '.' + PNG);
                ImageIO.write(img, PNG, pictureFile);
                final FileObject pictureFileObj = FileUtil.toFileObject(pictureFile);
                DataObject dobj = DataObject.find(pictureFileObj);
                OpenCookie oc = dobj.getLookup().lookup(OpenCookie.clreplaced);
                if (oc != null) {
                    oc.open();
                }
            } catch (IOException | TimeoutException | AdbCommandRejectedException ioe) {
                LOG.log(Level.INFO, null, ioe);
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(NbBundle.getMessage(EmulatorDeviceNode.clreplaced, "ERROR_ScreenShot"), NotifyDescriptor.ERROR_MESSAGE));
            }
        }

        @Override
        protected boolean enable(Node[] nodes) {
            if (nodes.length != 1) {
                return false;
            }
            return nodes[0].getLookup().lookup(IDevice.clreplaced) != null;
        }

        @Override
        public String getName() {
            return NbBundle.getMessage(ScreenShotAction.clreplaced, "TXT_ScreenShotAction");
        }

        @Override
        public HelpCtx getHelpCtx() {
            return new HelpCtx("org.nbandroid.netbeans.gradle.v2.adb.nodes.EmulatorDeviceNode");
        }
    }
}

19 Source : EmulatorDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public void deviceChanged(IDevice device, int changeType) {
    if (this.device.equals(device) && (changeType & IDevice.CHANGE_STATE) == IDevice.CHANGE_STATE) {
        this.updateDescription();
        firePropertySetsChange(null, null);
    }
}

19 Source : EmulatorDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public void deviceDisconnected(IDevice device) {
}

19 Source : EmulatorDeviceNode.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public void deviceConnected(IDevice device) {
}

19 Source : EmulatorControlSupport.java
with Apache License 2.0
from NBANDROIDTEAM

/**
 * @author radim
 */
public clreplaced EmulatorControlSupport {

    /**
     * Map between the display GSMmode and the internal tag used by the display.
     */
    private static final String[][] GSM_MODES = new String[][] { { "unregistered", GsmMode.UNREGISTERED.getTag() }, { "home", GsmMode.HOME.getTag() }, { "roaming", GsmMode.ROAMING.getTag() }, { "searching", GsmMode.SEARCHING.getTag() }, { "denied", GsmMode.DENIED.getTag() } };

    private static final String[] NETWORK_SPEEDS = new String[] { "Full", "GSM", "HSCSD", "GPRS", "EDGE", "UMTS", "HSDPA" };

    private static final String[] NETWORK_LATENCIES = new String[] { "None", "GPRS", "EDGE", "UMTS" };

    private final IDevice device;

    private EmulatorConsole console;

    /**
     * Device properties that can be controlled by tools.
     */
    public enum Control {

        VOICE(NbBundle.getMessage(EmulatorControlSupport.clreplaced, "PROP_Voice"), NbBundle.getMessage(EmulatorControlSupport.clreplaced, "DESC_Voice")), DATA(NbBundle.getMessage(EmulatorControlSupport.clreplaced, "PROP_Data"), NbBundle.getMessage(EmulatorControlSupport.clreplaced, "DESC_Data")), SPEED(NbBundle.getMessage(EmulatorControlSupport.clreplaced, "PROP_Speed"), NbBundle.getMessage(EmulatorControlSupport.clreplaced, "DESC_Speed")), LATENCY(NbBundle.getMessage(EmulatorControlSupport.clreplaced, "PROP_Latency"), NbBundle.getMessage(EmulatorControlSupport.clreplaced, "DESC_Latency"));

        private final String displayName;

        private final String description;

        private Control(String displayName, String description) {
            this.displayName = displayName;
            this.description = description;
        }

        public String getDescription() {
            return description;
        }

        public String getDisplayName() {
            return displayName;
        }
    }

    public EmulatorControlSupport(IDevice device) {
        this.device = device;
        // TODO init lazily?
        console = EmulatorConsole.getConsole(device);
    }

    public boolean hasConsole() {
        return console != null;
    }

    public String[] getTags(Control ctrl) {
        switch(ctrl) {
            // first two are equal
            case VOICE:
            case DATA:
                String[] tags = new String[GSM_MODES.length];
                for (int i = 0; i < GSM_MODES.length; i++) {
                    tags[i] = GSM_MODES[i][0];
                }
                return tags;
            case LATENCY:
                return NETWORK_LATENCIES;
            case SPEED:
                return NETWORK_SPEEDS;
            default:
                throw new IllegalStateException();
        }
    }

    public String getData(Control ctrl) {
        switch(ctrl) {
            // first two are equal
            case VOICE:
                GsmMode gsmModeVoice = console.getGsmStatus().voice;
                if (gsmModeVoice != null) {
                    for (int i = 0; i < GSM_MODES.length; i++) {
                        if (GSM_MODES[i][1].equals(gsmModeVoice.getTag())) {
                            return GSM_MODES[i][0];
                        }
                    }
                }
                break;
            case DATA:
                GsmMode gsmModeData = console.getGsmStatus().data;
                if (gsmModeData != null) {
                    for (int i = 0; i < GSM_MODES.length; i++) {
                        if (GSM_MODES[i][1].equals(gsmModeData.getTag())) {
                            return GSM_MODES[i][0];
                        }
                    }
                }
                break;
            case LATENCY:
                int latency = console.getNetworkStatus().latency;
                return latency != -1 ? NETWORK_LATENCIES[latency] : "";
            case SPEED:
                int speed = console.getNetworkStatus().speed;
                return speed != -1 ? NETWORK_SPEEDS[speed] : "";
            default:
                throw new IllegalStateException();
        }
        return "";
    }

    public void setData(Control ctrl, String val) {
        switch(ctrl) {
            // first two are equal
            case VOICE:
                if ("".equals(val)) {
                    // no-op
                    return;
                }
                for (int i = 0; i < GSM_MODES.length; i++) {
                    if (GSM_MODES[i][0].equals(val)) {
                        processCommandResult(console.setGsmVoiceMode(GsmMode.getEnum(GSM_MODES[i][1])));
                        return;
                    }
                }
                break;
            case DATA:
                if ("".equals(val)) {
                    // no-op
                    return;
                }
                for (int i = 0; i < GSM_MODES.length; i++) {
                    if (GSM_MODES[i][0].equals(val)) {
                        processCommandResult(console.setGsmDataMode(GsmMode.getEnum(GSM_MODES[i][1])));
                        return;
                    }
                }
                break;
            case LATENCY:
                for (int i = 0; i < NETWORK_LATENCIES.length; i++) {
                    if (NETWORK_LATENCIES[i].equals(val)) {
                        processCommandResult(console.setNetworkLatency(i));
                        return;
                    }
                }
                break;
            case SPEED:
                for (int i = 0; i < NETWORK_SPEEDS.length; i++) {
                    if (NETWORK_SPEEDS[i].equals(val)) {
                        processCommandResult(console.setNetworkSpeed(i));
                        return;
                    }
                }
                break;
            default:
                throw new IllegalStateException();
        }
    }

    private void processCommandResult(String result) {
        if (Objects.equal(EmulatorConsole.RESULT_OK, result)) {
            return;
        }
        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Emulator console : " + result, NotifyDescriptor.WARNING_MESSAGE));
    }

    public EmulatorConsole getConsole() {
        return console;
    }

    public IDevice getDevice() {
        return device;
    }
}

19 Source : EmptyLaunchAction.java
with Apache License 2.0
from NBANDROIDTEAM

@Override
public boolean doLaunch(LaunchInfo launchInfo, IDevice device, Project project, MainActivityConfiguration mainActivityConfiguration) {
    AndroidIO.getDefaultIO().getOut().println("No launch action requested.");
    return true;
}

19 Source : AvdSelector.java
with Apache License 2.0
from NBANDROIDTEAM

/**
 * Finds a device according to criteria from provided sources.
 *
 * @return
 */
LaunchData selectAvdName() {
    try {
        // look for all AVDs and find compatible ones
        // if there is just one use it
        // other count -> show UI
        avdManager.reloadAvds();
        if (prefferedAvdName != null) {
            AvdInfo candidateAvd = avdManager.getAvd(prefferedAvdName, true);
            // be optimistic if target is null
            if (target != null && !target.getVersion().canRun(candidateAvd.getAndroidVersion())) {
                candidateAvd = null;
            }
            if (candidateAvd != null) {
                // we can verify if there is a device with that AVD name
                // and start it if it is not but so far we leave it and start it from Ant
                for (IDevice device : devices) {
                    String deviceAvd = device.getAvdName();
                    if (deviceAvd != null && deviceAvd.equals(candidateAvd.getName())) {
                        // it is running and matches to what we want
                        return new LaunchData(candidateAvd, device);
                    }
                }
                // matchingAVD exists but is not running yet
                return new LaunchData(candidateAvd, null);
            }
        }
        // no preffered AVD or no valid, still it is auto so do our best
        // try ADB to see if there is a good match
        // true if we find a device but don't know if it can be used
        boolean hasUnknownDevice = false;
        Map<IDevice, AvdInfo> compatibleAvds = new HashMap<IDevice, AvdInfo>();
        for (IDevice device : devices) {
            String deviceAvd = device.getAvdName();
            if (deviceAvd != null) {
                // physical devices return null.
                AvdInfo info = avdManager.getAvd(deviceAvd, true);
                if (info != null && (target == null || target.getVersion().canRun(info.getAndroidVersion()))) {
                    compatibleAvds.put(device, info);
                }
            } else {
                if (target == null || target.isPlatform()) {
                    // means this can run on any device as long
                    // as api level is high enough
                    String apiString = device.getProperty(LocalPlatformPkgInfo.PROP_VERSION_SDK);
                    try {
                        int apiNumber = Integer.parseInt(apiString);
                        if (target == null || apiNumber >= target.getVersion().getApiLevel()) {
                            // device is compatible with project
                            compatibleAvds.put(device, null);
                            continue;
                        }
                    } catch (NumberFormatException e) {
                    // do nothing, we'll consider it a non compatible device below.
                    }
                }
                hasUnknownDevice = true;
            }
        }
        if (!hasUnknownDevice) {
            LOG.log(Level.FINE, "compatible avds: {0}", compatibleAvds);
            if (compatibleAvds.isEmpty()) {
                AvdInfo matchingAvd = findAvdForTarget();
                return matchingAvd != null ? new LaunchData(matchingAvd, null) : null;
            } else if (compatibleAvds.size() == 1) {
                Map.Entry<IDevice, AvdInfo> entry = compatibleAvds.entrySet().iterator().next();
                // there is one known devices and it is compatible
                return new LaunchData(entry.getValue(), entry.getKey());
            }
        }
    } catch (SAXParseException ex) {
        Exceptions.attachMessage(ex, "Cannot initialize list of devices.");
        Exceptions.printStackTrace(ex);
    } catch (AndroidLocationException ex) {
        Exceptions.attachMessage(ex, "Cannot initialize list of devices.");
        Exceptions.printStackTrace(ex);
    }
    return null;
}

19 Source : LogSourceManager.java
with Apache License 2.0
from josesamuel

@Override
public void deviceConnected(final IDevice device) {
    updateDeviceList();
}

19 Source : LogSourceManager.java
with Apache License 2.0
from josesamuel

/**
 * Updates the device list
 */
private void updateDeviceList() {
    if (myBridge != null) {
        java.util.List<IDevice> deviceList = new ArrayList<>();
        for (IDevice device : myBridge.getDevices()) {
            deviceList.add(device);
            DeviceLogSource deviceLogSource = getDeviceSource(device);
            if (deviceLogSource == null) {
                deviceLogSource = new DeviceLogSource(device);
                deviceLogSourcesMap.put(device, deviceLogSource);
            }
        }
        for (IDevice device : deviceLogSourcesMap.keySet()) {
            if (!deviceList.contains(device)) {
                deviceLogSourcesMap.get(device).getLogProvider().dispose();
                deviceLogSourcesMap.remove(device);
            }
        }
        logSourceManagerListener.onSourceListChanged();
    }
}

19 Source : LogSourceManager.java
with Apache License 2.0
from josesamuel

/**
 * Returns the {@link DeviceLogSource} for the given device
 */
private DeviceLogSource getDeviceSource(IDevice device) {
    return deviceLogSourcesMap.get(device);
}

19 Source : LogSourceManager.java
with Apache License 2.0
from josesamuel

@Override
public void deviceDisconnected(final IDevice device) {
    updateDeviceList();
}

19 Source : LogSourceManager.java
with Apache License 2.0
from josesamuel

/**
 * Returns the {@link LogSource} for the given device, creates as needed
 */
private LogSource getSource(IDevice device) {
    LogSource source = null;
    if (device != null) {
        source = getDeviceSource(device);
        if (source == null && device instanceof FileDevice) {
            source = getFileSource(((FileDevice) device).getFile());
        }
    }
    return source;
}

19 Source : LogSourceManager.java
with Apache License 2.0
from josesamuel

@Override
public void deviceChanged(final IDevice device, final int changeMask) {
    if ((changeMask & IDevice.CHANGE_STATE) != 0) {
        updateDeviceList();
    }
    if (device != null) {
        deviceSelectionListener.deviceChanged(device, changeMask);
    }
}

19 Source : DeviceLogSource.java
with Apache License 2.0
from josesamuel

public clreplaced DeviceLogSource implements LogSource {

    private IDevice device;

    private DeviceLogDataProvider logDataProvider;

    public DeviceLogSource(IDevice device) {
        this.device = device;
        this.logDataProvider = new DeviceLogDataProvider(device);
    }

    @Override
    public IDevice getSource() {
        return device;
    }

    @Override
    public LogDataProvider getLogProvider() {
        return logDataProvider;
    }

    @Override
    public String toString() {
        return device.getSerialNumber() + " " + super.toString();
    }
}

19 Source : DeviceLogDataProvider.java
with Apache License 2.0
from josesamuel

/**
 * {@link LogDataProvider} for actual device
 */
public clreplaced DeviceLogDataProvider implements LogDataProvider, AndroidLogcatService.LogcatListener {

    private LogCatHeader myActiveHeader;

    private LogDataListener logListener;

    private IDevice device;

    /**
     * Initialize this with the given device
     */
    DeviceLogDataProvider(IDevice device) {
        this.device = device;
    }

    @Override
    public void registerLogListener(LogDataListener logListener) {
        this.logListener = logListener;
        AndroidLogcatService.getInstance().addListener(device, this, true);
        updateProcessList();
    }

    @Override
    public void unRegisterLogListener(LogDataListener logListener) {
        this.logListener = null;
        AndroidLogcatService.getInstance().removeListener(device, this);
    }

    @Override
    public void onLogLineReceived(@NotNull LogCatMessage line) {
        try {
            LogProcess logProcess = new LogProcess();
            logProcess.setProcessID(line.getPid());
            String appName = line.getAppName();
            if (appName == null || appName.isEmpty() || appName.equals("?")) {
                appName = line.getTag();
                if (appName == null || appName.isEmpty() || appName.equals("?")) {
                    appName = "TAG";
                }
            }
            logProcess.setProcessName(appName);
            String message = null;
            if (!line.getHeader().equals(myActiveHeader)) {
                myActiveHeader = line.getHeader();
                message = AndroidLogcatFormatter.formatMessageFull(myActiveHeader, line.getMessage());
            } else {
                message = AndroidLogcatFormatter.formatContinuation(line.getMessage());
            }
            if (message != null) {
                notifyLog(message, logProcess);
            }
        } catch (Exception ex) {
            logListener.debug(ex.getMessage());
        }
    }

    /**
     * Notify a new line is added
     */
    private void notifyLog(String logLine, LogProcess process) {
        UIUtil.invokeLaterIfNeeded(() -> {
            try {
                if (logListener != null) {
                    logListener.onLogLine(logLine, process);
                }
            } catch (Exception ignored) {
            }
        });
    }

    @Override
    public void onCleared() {
        UIUtil.invokeLaterIfNeeded(() -> {
            if (logListener != null) {
                logListener.onCleared();
            }
        });
    }

    /**
     * Clean up
     */
    public void dispose() {
        AndroidLogcatService.getInstance().removeListener(device, this);
        this.logListener = null;
    }

    /**
     * Updates the process list
     */
    public void updateProcessList() {
        if (logListener != null) {
            UIUtil.invokeLaterIfNeeded(() -> {
                try {
                    if (device != null && logListener != null) {
                        List<Client> clients = Lists.newArrayList(device.getClients());
                        clients.sort(new ClientCellRenderer.ClientComparator());
                        logListener.onProcessList(toLogProcess(clients));
                    }
                } catch (Exception ignored) {
                }
            });
        }
    }

    /**
     * Convert list of {@link Client} to list of {@link LogProcess}
     */
    private Set<LogProcess> toLogProcess(List<Client> clientList) {
        Set<LogProcess> logProcesses = new HashSet<>();
        for (Client client : clientList) {
            if (client != null) {
                logProcesses.add(new LogProcess(client));
            }
        }
        return logProcesses;
    }
}

19 Source : Mirror.java
with Apache License 2.0
from huanglqweiwei

private JFrame createJFrame(IDevice device) {
    JFrame jFrame = new JFrame(device.getName());
    jFrame.setSize(WIDTH, HEIGHT + 60);
    jFrame.addWindowListener(this);
    jFrame.setLayout(new BorderLayout());
    jFrame.setResizable(false);
    return jFrame;
}

19 Source : DeviceItem.java
with Apache License 2.0
from huanglqweiwei

public clreplaced DeviceItem {

    private static final String TAG = "DeviceItem";

    private IDevice mIDevice;

    private JFrame mJFrame;

    private JButton mJButton;

    private Mirror mMirror;

    private static int COUNT = 0;

    private int index;

    public DeviceItem(IDevice iDevice, JFrame jFrame) {
        mIDevice = iDevice;
        mJFrame = jFrame;
        COUNT++;
        index = COUNT;
    }

    public void setDevice(IDevice iDevice) {
        mIDevice = iDevice;
    }

    public JButton getJButton() {
        if (mJButton == null) {
            mJButton = new JButton(mIDevice.getName());
            mJButton.setSize(288, 40);
            mJButton.addActionListener(new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Log.d(TAG, "actionPerformed");
                    if (mMirror == null) {
                        mMirror = new Mirror(mIDevice, mJFrame, index);
                    }
                    mMirror.show(mIDevice);
                }
            });
        }
        return mJButton;
    }

    public void stop() {
        if (mMirror != null) {
            mMirror.stop();
            mMirror = null;
        }
    }
}

19 Source : DeviceItem.java
with Apache License 2.0
from huanglqweiwei

public void setDevice(IDevice iDevice) {
    mIDevice = iDevice;
}

19 Source : SingleTouch.java
with Apache License 2.0
from huanglqweiwei

public void start(IDevice device, int port) {
    mPort = port;
    mDevice = device;
    Tools.sExecutor.submit(this);
    mStopped = false;
}

19 Source : Application.java
with Apache License 2.0
from huanglqweiwei

@Override
public void onDeviceDisconnect(IDevice iDevice) {
    Log.d(TAG, "deviceDisconnected : " + iDevice);
    if (mDeviceItems != null) {
        DeviceItem deviceItem = mDeviceItems.get(iDevice.getSerialNumber());
        if (deviceItem != null) {
            deviceItem.stop();
            mJPanel.remove(deviceItem.getJButton());
            SwingUtilities.updateComponentTreeUI(mJPanel);
        }
    }
}

19 Source : Application.java
with Apache License 2.0
from huanglqweiwei

@Override
public void onDeviceConnect(IDevice iDevice) {
    Log.d(TAG, "deviceConnected : " + iDevice);
    if (mDeviceItems == null) {
        mDeviceItems = new HashMap<String, DeviceItem>();
    }
    DeviceItem deviceItem = mDeviceItems.get(iDevice.getSerialNumber());
    if (deviceItem == null) {
        deviceItem = new DeviceItem(iDevice, mJFrame);
        mDeviceItems.put(iDevice.getSerialNumber(), deviceItem);
    } else {
        deviceItem.setDevice(iDevice);
    }
    addItem(deviceItem.getJButton());
}

19 Source : AndroidBridge.java
with Apache License 2.0
from huanglqweiwei

@Override
public void deviceChanged(IDevice iDevice, int mark) {
    Log.d(TAG, "deviceChanged : " + iDevice);
    if (mark == IDevice.CHANGE_BUILD_INFO) {
        if (mChangeListener != null) {
            mChangeListener.onDeviceConnect(iDevice);
        }
    }
}

19 Source : AndroidBridge.java
with Apache License 2.0
from huanglqweiwei

@Override
public void deviceDisconnected(IDevice iDevice) {
    if (mChangeListener != null) {
        mChangeListener.onDeviceDisconnect(iDevice);
    }
}

19 Source : AndroidBridge.java
with Apache License 2.0
from huanglqweiwei

@Override
public void deviceConnected(IDevice iDevice) {
}

19 Source : DdmlibDevice.java
with Apache License 2.0
from google

/**
 * Ddmlib-backed implementation of the {@link Device}.
 */
public clreplaced DdmlibDevice extends Device {

    private final IDevice device;

    private static final int ADB_TIMEOUT_MS = 60000;

    private static final String DEVICE_FEATURES_COMMAND = "pm list features";

    private static final String GL_EXTENSIONS_COMMAND = "dumpsys SurfaceFlinger";

    private final DeviceFeaturesParser deviceFeaturesParser = new DeviceFeaturesParser();

    private final GlExtensionsParser glExtensionsParser = new GlExtensionsParser();

    public DdmlibDevice(IDevice device) {
        this.device = device;
    }

    @Override
    public DeviceState getState() {
        return device.getState();
    }

    @Override
    public AndroidVersion getVersion() {
        return device.getVersion();
    }

    @Override
    public ImmutableList<String> getAbis() {
        return ImmutableList.copyOf(device.getAbis());
    }

    @Override
    public int getDensity() {
        return device.getDensity();
    }

    @Override
    public String getSerialNumber() {
        return device.getSerialNumber();
    }

    @Override
    public Optional<String> getProperty(String propertyName) {
        return Optional.ofNullable(device.getProperty(propertyName));
    }

    @Override
    public ImmutableList<String> getDeviceFeatures() {
        return deviceFeaturesParser.parse(new AdbShellCommandTask(this, DEVICE_FEATURES_COMMAND).execute(ADB_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    }

    @Override
    public ImmutableList<String> getGlExtensions() {
        return glExtensionsParser.parse(new AdbShellCommandTask(this, GL_EXTENSIONS_COMMAND).execute(ADB_TIMEOUT_MS, TimeUnit.MILLISECONDS));
    }

    @Override
    public void executeShellCommand(String command, IShellOutputReceiver receiver, long maxTimeToOutputResponse, TimeUnit maxTimeUnits) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
        device.executeShellCommand(command, receiver, maxTimeToOutputResponse, maxTimeUnits);
    }

    @Override
    public void installApks(ImmutableList<Path> apks, InstallOptions installOptions) {
        ImmutableList<File> apkFiles = apks.stream().map(Path::toFile).collect(toImmutableList());
        ImmutableList.Builder<String> extraArgs = ImmutableList.builder();
        if (installOptions.getAllowDowngrade()) {
            extraArgs.add("-d");
        }
        if (installOptions.getAllowTestOnly()) {
            extraArgs.add("-t");
        }
        try {
            if (getVersion().isGreaterOrEqualThan(AndroidVersion.ALLOW_SPLIT_APK_INSTALLATION.getApiLevel())) {
                device.installPackages(apkFiles, installOptions.getAllowReinstall(), extraArgs.build(), installOptions.getTimeout().toMillis(), TimeUnit.MILLISECONDS);
            } else {
                device.installPackage(Iterables.getOnlyElement(apkFiles).toString(), installOptions.getAllowReinstall(), extraArgs.build().toArray(new String[0]));
            }
        } catch (InstallException e) {
            throw CommandExecutionException.builder().withCause(e).withInternalMessage("Installation of the app failed.").build();
        }
    }

    @Override
    public void pushApks(ImmutableList<Path> apks, PushOptions pushOptions) {
        String splitsPath = pushOptions.getDestinationPath();
        checkArgument(!splitsPath.isEmpty(), "Splits path cannot be empty.");
        RemoteCommandExecutor commandExecutor = new RemoteCommandExecutor(this, pushOptions.getTimeout().toMillis(), System.err);
        try {
            // There are two different flows, depending on if the path is absolute or not...
            if (!splitsPath.startsWith("/")) {
                // Path is relative, so we're going to try to push it to the app's external dir
                String packageName = pushOptions.getPackageName().orElseThrow(() -> CommandExecutionException.builder().withInternalMessage("PushOptions.packageName must be set for relative paths.").build());
                splitsPath = joinUnixPaths("/sdcard/Android/data/", packageName, "files", splitsPath);
            }
            // Now the path is absolute. We replacedume it's pointing to a location writeable by ADB shell.
            // It shouldn't point to app's private directory.
            // Some clean up first. Remove the destination dir if flag is set...
            if (pushOptions.getClearDestinationPath()) {
                commandExecutor.executeAndPrint("rm -rf %s", splitsPath);
            }
            // ... and recreate it, making sure the destination dir is empty.
            // We don't want splits from previous runs in the directory.
            // There isn't a nice way to test if dir is empty in shell, but rmdir will return error
            commandExecutor.executeAndPrint("mkdir -p %s && rmdir %s && mkdir -p %s", splitsPath, splitsPath, splitsPath);
            // Try to push files normally. Will fail if ADB shell doesn't have permission to write.
            for (Path path : apks) {
                device.pushFile(path.toFile().getAbsolutePath(), joinUnixPaths(splitsPath, path.getFileName().toString()));
                System.err.printf("Pushed \"%s\"%n", joinUnixPaths(splitsPath, path.getFileName().toString()));
            }
        } catch (IOException | TimeoutException | SyncException | AdbCommandRejectedException | ShellCommandUnresponsiveException e) {
            throw CommandExecutionException.builder().withCause(e).withInternalMessage("Pushing additional splits for local testing failed. Your app might still have been" + " installed correctly, but you won't be able to test dynamic modules.").build();
        }
    }

    @Override
    public Path syncPackageToDevice(Path localFilePath) throws TimeoutException, AdbCommandRejectedException, SyncException, IOException {
        return Paths.get(device.syncPackageToDevice(localFilePath.toFile().getAbsolutePath()));
    }

    @Override
    public void removeRemotePackage(Path remoteFilePath) throws InstallException {
        device.removeRemotePackage(remoteFilePath.toString());
    }

    static clreplaced RemoteCommandExecutor {

        private final Device device;

        private final MultiLineReceiver receiver;

        private final long timeout;

        private final PrintStream out;

        private String lastOutputLine;

        RemoteCommandExecutor(Device device, long timeout, PrintStream out) {
            this.device = device;
            this.timeout = timeout;
            this.out = out;
            this.receiver = new MultiLineReceiver() {

                @Override
                public void processNewLines(String[] lines) {
                    for (String line : lines) {
                        if (!line.isEmpty()) {
                            out.println("ADB >> " + line);
                            lastOutputLine = line;
                        }
                    }
                }

                @Override
                public boolean isCancelled() {
                    return false;
                }
            };
        }

        @FormatMethod
        private void executeAndPrint(String commandFormat, String... args) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
            String command = formatCommandWithArgs(commandFormat, args);
            lastOutputLine = null;
            out.println("ADB << " + command);
            // ExecuteShellCommand would only tell us about ADB errors, and NOT the actual shell commands
            // We need another way to check exit values of the commands we run.
            // By adding " && echo OK" we can make sure "OK" is printed if the cmd executed successfully.
            device.executeShellCommand(command + " && echo OK", receiver, timeout, TimeUnit.MILLISECONDS);
            if (!"OK".equals(lastOutputLine)) {
                throw new IOException("ADB command failed.");
            }
        }

        /**
         * Returns the string in single quotes, with any single quotes in the string escaped.
         */
        static String escapeAndSingleQuote(String string) {
            return "'" + string.replace("'", "'\\''") + "'";
        }

        /**
         * Formats the command string, replacing %s argument placeholders with escaped and single quoted
         * args. This was made to work with Strings only, so format your args beforehand.
         */
        @FormatMethod
        static String formatCommandWithArgs(String command, String... args) {
            return String.format(command, Arrays.stream(args).map(RemoteCommandExecutor::escapeAndSingleQuote).toArray());
        }
    }

    // We can't rely on Path and friends if running on Windows, emulator always needs UNIX paths
    static String joinUnixPaths(String... parts) {
        StringBuilder sb = new StringBuilder();
        for (String part : parts) {
            if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
                sb.append('/');
            }
            sb.append(part);
        }
        return sb.toString();
    }
}

19 Source : CatdeaLogcatView.java
with Apache License 2.0
from Cybr0sis

/**
 * @author cybrosis
 */
public clreplaced CatdeaLogcatView implements Disposable {

    private static final AnActionEvent FAKE_ACTION_EVENT = new TestActionEvent();

    private final Project project;

    private final DeviceContext deviceContext;

    private final EditorEx editor;

    private volatile IDevice device;

    private CycledPsiFile psiFile;

    private AnAction[] actions;

    private final ScrollToTheEndToolbarAction scrollToTheEndAction;

    private final AndroidLogcatService.LogcatListener logcatListener = new AndroidLogcatService.LogcatListener() {

        @Override
        public void onLogLineReceived(@NotNull LogCatMessage line) {
            if (!filter(line))
                return;
            final String log = convert(line);
            final boolean isScrollToTheEnd = ApplicationManager.getApplication().runReadAction((Computable<Boolean>) () -> scrollToTheEndAction.isSelected(FAKE_ACTION_EVENT));
            final PsiElement[] children = ApplicationManager.getApplication().runReadAction((Computable<PsiElement[]>) () -> PsiTreeUtil.collectElements(PsiFileFactory.getInstance(project).createFileFromText(CatdeaLanguage.INSTANCE, log), it -> PsiTreeUtil.instanceOf(it, PsiCatdeaEntry.clreplaced, PsiWhiteSpace.clreplaced)));
            executeCommandLaterInWriteAction(project, () -> {
                psiFile.append(children);
                if (isScrollToTheEnd)
                    scrollToTheEndAction.setSelected(FAKE_ACTION_EVENT, true);
            });
        }

        @Override
        public void onCleared() {
            executeCommandLaterInWriteAction(project, () -> {
                psiFile.clear();
            });
        }
    };

    /**
     * @see LogcatConsoleActionsPostProcessor.ClearLogCatAction
     */
    @SuppressWarnings("JavadocReference")
    private final clreplaced ClearLogCatAction extends DumbAwareAction {

        private ClearLogCatAction() {
            super(AndroidBundle.message("android.logcat.clear.log.action.replacedle"), AndroidBundle.message("android.logcat.clear.log.action.tooltip"), AllIcons.Actions.GC);
        }

        @Override
        public void update(@NotNull AnActionEvent e) {
            e.getPresentation().setEnabled(editor.getDoreplacedent().getTextLength() != 0);
        }

        @Override
        public void actionPerformed(@NotNull AnActionEvent e) {
            final IDevice device = deviceContext.getSelectedDevice();
            if (device != null) {
                AndroidLogcatService.getInstance().clearLogcat(device, project);
            }
        }
    }

    CatdeaLogcatView(@NotNull Project project, @NotNull DeviceContext deviceContext) {
        this.project = project;
        this.deviceContext = deviceContext;
        // Use PSI to support references and navigation to source code from log entry
        final PsiFile dummy = PsiFileFactory.getInstance(project).createFileFromText("_dummy_", CatdeaFileType.INSTANCE, "");
        psiFile = new CycledPsiFile(dummy);
        final Doreplacedent doreplacedent = dummy.getViewProvider().getDoreplacedent();
        replacedert doreplacedent != null;
        UndoUtil.disableUndoFor(doreplacedent);
        editor = (EditorEx) EditorFactory.getInstance().createViewer(doreplacedent, project, EditorKind.CONSOLE);
        editor.getSettings().setAutoCodeFoldingEnabled(false);
        editor.getSettings().setLineMarkerAreaShown(false);
        ConsoleViewUtil.setupConsoleEditor(editor, false, false);
        editor.setHighlighter(new LexerEditorHighlighter(new CatdeaSyntaxHighlighter(), editor.getColorsScheme()));
        scrollToTheEndAction = new ScrollToTheEndToolbarAction(editor);
        actions = new AnAction[] { new ClearLogCatAction(), new ToggleUseSoftWrapsToolbarAction(SoftWrapAppliancePlaces.CONSOLE) {

            @Override
            protected Editor getEditor(@NotNull AnActionEvent e) {
                return editor;
            }
        }, scrollToTheEndAction };
        deviceContext.addListener(new DeviceContext.DeviceSelectionListener() {

            @Override
            public void deviceSelected(@Nullable IDevice device) {
                notifyDeviceUpdated(false);
            }

            @Override
            public void deviceChanged(@NotNull IDevice device, int changeMask) {
                if (CatdeaLogcatView.this.device == device && ((changeMask & IDevice.CHANGE_STATE) == IDevice.CHANGE_STATE)) {
                    notifyDeviceUpdated(true);
                }
            }

            @Override
            public void clientSelected(@Nullable Client c) {
            }
        }, this);
        Disposer.register(project, this);
        updateLogConsole();
    }

    public AnAction[] getActions() {
        return actions;
    }

    public Editor getEditor() {
        return editor;
    }

    private void stopListening() {
        if (device != null) {
            AndroidLogcatService.getInstance().removeListener(device, logcatListener);
        }
        device = null;
    }

    /**
     * @see AndroidLogcatView#notifyDeviceUpdated(boolean)
     */
    @SuppressWarnings("JavadocReference")
    private void notifyDeviceUpdated(final boolean forceReconnect) {
        UIUtil.invokeAndWaitIfNeeded((Runnable) () -> {
            if (project.isDisposed())
                return;
            if (forceReconnect)
                stopListening();
            updateLogConsole();
        });
    }

    /**
     * @see AndroidLogcatView#updateLogConsole()
     */
    @SuppressWarnings("JavadocReference")
    private void updateLogConsole() {
        final IDevice selectedDevice = deviceContext.getSelectedDevice();
        if (device == selectedDevice)
            return;
        stopListening();
        logcatListener.onCleared();
        device = selectedDevice;
        AndroidLogcatService.getInstance().addListener(device, logcatListener);
    }

    private boolean filter(@NotNull LogCatMessage message) {
        if (deviceContext.getSelectedDevice() == null)
            return false;
        final Client client = deviceContext.getSelectedClient();
        return client != null && client.getClientData().getPid() == message.getHeader().getPid();
    }

    private static String convert(@NotNull LogCatMessage message) {
        final LogCatHeader header = message.getHeader();
        return String.format("%s %d-%d/%s %s/%s: %s\n", CompatibilityUtil.LogcatHeader.getTimestamp(header), header.getPid(), header.getTid(), header.getAppName(), Character.toUpperCase(header.getLogLevel().getPriorityLetter()), header.getTag(), message.getMessage());
    }

    @Override
    public void dispose() {
        EditorFactory.getInstance().releaseEditor(editor);
        stopListening();
        logcatListener.onCleared();
    }

    private static void executeCommandLaterInWriteAction(Project project, Runnable runnable) {
        ApplicationManager.getApplication().invokeLater(() -> {
            if (project.isDisposed())
                return;
            CommandProcessor.getInstance().executeCommand(project, () -> {
                ApplicationManager.getApplication().runWriteAction(runnable);
            }, null, null);
        });
    }
}

19 Source : ScriptService.java
with GNU General Public License v3.0
from cxplan

@Override
public boolean startScriptService(final IDevice device) {
    int pid = AdbUtil.checkApplicationProcess(device, CommonUtil.PROCESS_NAME_SCRIPT);
    if (pid > 0) {
        logger.info("The main process existed already: " + pid);
        return true;
    }
    final String deviceId = AdbUtil.getDeviceId(device);
    final String cmd = buildStartScriptCmd(device);
    synchronized (device) {
        if (startedDeviceSet.contains(deviceId)) {
            return false;
        }
        Thread th = new Thread("ScriptService Thread-" + deviceId) {

            @Override
            public void run() {
                try {
                    AdbUtil.shellBlockingCommand(cmd, device, 0);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                startedDeviceSet.remove(deviceId);
                logger.info("The script process is finished: {}", deviceId);
            }
        };
        th.start();
        startedDeviceSet.add(deviceId);
    }
    return false;
}

19 Source : ScriptService.java
with GNU General Public License v3.0
from cxplan

private String buildStartScriptCmd(IDevice device) {
    // app_process -Djava.clreplaced.path="/system/framework/am.jar" /system/bin --nice-name=cxplan.cxscript com.android.commands.am.Am instrument
    // -w com.cxplan.projection.mediate.test/android.support.test.runner.AndroidJUnitRunner
    String scriptPackagePath = AdbUtil.getPackagePath(CommonUtil.PACKAGE_SCRIPT, device);
    if (scriptPackagePath == null) {
        // is not installed
        throw new RuntimeException("The script package is not installed: " + AdbUtil.getDeviceId(device));
    }
    StringBuilder sb = new StringBuilder("app_process -Djava.clreplaced.path=\"/system/framework/am.jar\" /system/bin --nice-name=");
    sb.append(CommonUtil.PROCESS_NAME_SCRIPT).append(" com.android.commands.am.Am instrument -w com.cxplan.projection.mediate.test/android.support.test.runner.AndroidJUnitRunner");
    return sb.toString();
}

19 Source : ControllerInfrastructureService.java
with GNU General Public License v3.0
from cxplan

private String buildMainCmd(IDevice device) {
    // app_process -Djava.clreplaced.path=/data/app/com.cxplan.mediate-1/base.apk
    // /data/local/tmp --nice-name=com.cxplan.projection.mediate com.cxplan.mediate.process.Main
    String mainPackagePath = AdbUtil.getPackagePath(CommonUtil.PACKAGE_MAIN, device);
    if (mainPackagePath == null) {
        // is not installed
        throw new RuntimeException("The main package is not installed: " + AdbUtil.getDeviceId(device));
    }
    StringBuilder sb = new StringBuilder("app_process -Djava.clreplaced.path=");
    sb.append(mainPackagePath).append(" /data/local/tmp --nice-name=").append(CommonUtil.PROCESS_NAME_MAIN).append(" com.cxplan.projection.mediate.process.Main");
    return sb.toString();
}

19 Source : BlazeAndroidTestRunContext.java
with Apache License 2.0
from bazelbuild

@Nullable
@Override
public Integer getUserId(IDevice device, ConsolePrinter consolePrinter) {
    return null;
}

19 Source : BlazeAndroidBinaryMobileInstallRunContextBase.java
with Apache License 2.0
from bazelbuild

@Nullable
@Override
public Integer getUserId(IDevice device, ConsolePrinter consolePrinter) throws ExecutionException {
    return UserIdHelper.getUserIdFromConfigurationState(device, consolePrinter, configState);
}

19 Source : BlazeDefaultActivityLocator.java
with Apache License 2.0
from bazelbuild

@Override
public String getQualifiedActivityName(@NotNull IDevice device) throws ActivityLocatorException {
    if (manifest == null) {
        throw new ActivityLocatorException("Could not locate merged manifest");
    }
    if (manifest.defaultActivityClreplacedName == null) {
        throw new ActivityLocatorException("Could not locate default activity to launch.");
    }
    return manifest.defaultActivityClreplacedName;
}

18 Source : EventLogParser.java
with GNU General Public License v3.0
from tranleduy2000

/**
 * 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 {
        // $NON-NLS-1$
        device.executeShellCommand(// $NON-NLS-1$
        "cat " + EVENT_TAG_MAP_FILE, 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;
}

See More Examples