如何在build.gradle中查询所有连接的设备?

时间:2015-12-09 18:16:33

标签: android gradle android-gradle adb build.gradle

我正在尝试在build.gradle中编写一个在所有连接的设备上执行shell命令的任务。但是,当我运行我的任务时,我得到了臭名昭着的“连接多个设备”错误。

task(myTask, type: Exec) {
    doFirst {
        println 'myTask'
        commandLine 'adb', 'shell', 'my command'
    }
}

这是可以理解的,因为我没有指定使用-s运行哪个设备。但是,我注意到installDebug任务将在所有连接的设备上执行其命令(在所有设备上安装debug .apk)。

Android插件中是否有API返回我可以迭代的设备ID集合?

2 个答案:

答案 0 :(得分:4)

是的。您可以查看Android Gradle插件source here,其中包含以下内容:

import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.IDevice

// ...    

AndroidDebugBridge.initIfNeeded(false /*clientSupport*/)
AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(android.getAdbExe().absolutePath,
        false /*forceNewBridge*/)

long timeOut = 30000 // 30 sec
int sleepTime = 1000
while (!bridge.hasInitialDeviceList() && timeOut > 0) {
    sleep(sleepTime)
    timeOut -= sleepTime
}
if (timeOut <= 0 && !bridge.hasInitialDeviceList()) {
    throw new RuntimeException("Timeout getting device list.", null)
}
IDevice[] devices = bridge.devices
if (devices.length == 0) {
    throw new RuntimeException("No connected devices!", null)
}

File destination = project.file("$project.buildDir/outputs/screenshots")
delete destination

for (IDevice device : devices) {
    // iterate over your devices here ;)
}

另外你会注意到adb的getter也可以在上面的循环中使用:

project.exec {
            executable = android.getAdbExe()
            args '-s'
            args "$device.serialNumber"
}

答案 1 :(得分:1)

旧线程,但也许它可以在某些时候帮助某人。

正如David Medenjak已经提到的,android.ddmlib就是解决方案。 您可以像下面这样使用它:

在yourscript.gradle中:

import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.IDevice
import com.android.ddmlib.NullOutputReceiver

task pressPower {

    description = "Press the power button of a device using the adb."

    AndroidDebugBridge.initIfNeeded(false)
    def bridge = AndroidDebugBridge.createBridge(android.adbExecutable.path, false)

    doLast {
        bridge.devices.each {
            it.executeShellCommand("input keyevent 26", NullOutputReceiver.receiver)
        }
    }
}

其中&#34;输入keyevent 26&#34;对应于shell命令./adb shell input keyevent 26.

如果您想使用shell的输出,可以使用下面的CollectingOutputReceiver

import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.IDevice
import com.android.ddmlib.CollectingOutputReceiver

task getAnimationValue {

    description = "Get the Value for the window animation scale."

    AndroidDebugBridge.initIfNeeded(false)
    def bridge = AndroidDebugBridge.createBridge(android.adbExecutable.path, false)
    def receiver = CollectingOutputReceiver.newInstance()

    doLast{
        bridge.devices.each {
            it.executeShellCommand("settings get global window_animation_scale", receiver)
            println "Value: ${receiver.getOutput()}"
        }
    }
}

任务打印由receiver.getOutput()收集的窗口动画比例的值。

相关问题