Android Debug Bridge 如其名,是连接 Android Device/Emulator 的桥梁,IDE 如 AS,ADT,Android 测试框架 Appium,Selendroid 无不 heavy 的依靠 adb。而 ddmlib 无疑是最好的 adb api. 在刚使用时略复杂,好在有个 lib 让它的使用变得简单。
携程在构建无线测试框架的时候,非常重视 ddmlib API 的打造,充分参考 Selendroid/Appium 的实现,毕竟这是基础的基础,而不是各种乱造。
Maven
<dependency>
<groupId>com.github.cosysoft</groupId>
<artifactId>device-api</artifactId>
<version>0.9.1</version>
</dependency>
Gradle
dependencies {
compile 'com.github.cosysoft:device-api:0.9.1'
}
public class EchoTest {
@Test
public void takeDevices() {
TreeSet<AndroidDevice> devices = AndroidDeviceStore.getInstance()
.getDevices();
AndroidDevice device = devices.pollFirst();
System.out.println(device.getName());
}
}
BufferedImage image = device.takeScreenshot();
String imagePath = new File(System.getProperty("java.io.tmpdir"),
"screenshot.png").getAbsolutePath();
ImageUtils.writeToFile(image, imagePath);
AndroidApp app = new DefaultAndroidApp(new File(
"d:\\uat\\com.android.chrome.apk"));
device.install(app);
if (device.isInstalled(app)) {
device.uninstall(app);
}
final LogCatFilter filter = new LogCatFilter("", "", "com.android", "",
"", LogLevel.WARN);
final LogCatListener lcl = new LogCatListener() {
@Override
public void log(List<LogCatMessage> msgList) {
for (LogCatMessage msg : msgList) {
if (filter.matches(msg)) {
System.out.println(msg);
}
}
}
};
device.addLogCatListener(lcl);
Thread.sleep(60000);
List<ClientDataInfo> clientDataInfos = device.getClientDatasInfo();
for (ClientDataInfo client : clientDataInfos) {
System.out.println(client.getName());
System.out.println(client.getPid());
}