通过ddmlib实现截图、获取手机相关信息
Google Android SDK中有一个ddmlib的扩展库,位于sdk/tools/lib/ddmlib.jar。我们引用这个库,就可以实现对手机的截屏以及获取手机的相关信息。
获取到device对象后可以通过device.getScreenshot()来实现截图。因为所截图片为RawImage所以我们需要将他转换为PNG格式:
通过device对象,我们还可以安装、卸载应用:
Google Android SDK中有一个ddmlib的扩展库,位于sdk/tools/lib/ddmlib.jar。我们引用这个库,就可以实现对手机的截屏以及获取手机的相关信息。
引入ddmlib库之后,首先要找到设备对象,所以先要获得到device[]列表,再从列表中取出所需要的设备对象:
public IDevice getDevice(String id) {
AndroidDebugBridge bridge = AndroidDebugBridge
.createBridge("adb", true);
waitDevicesList(bridge);
IDevice devices[] = bridge.getDevices();
for (IDevice onlinedeivce : devices) {
if (onlinedeivce.getSerialNumber().equals(id))
return onlinedeivce;
}
return null;
}
获取到device对象后可以通过device.getScreenshot()来实现截图。因为所截图片为RawImage所以我们需要将他转换为PNG格式:
public boolean getScreenShot(IDevice device, String filepath) {
RawImage rawScreen = null;
try {
rawScreen = device.getScreenshot();
} catch (AdbCommandRejectedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (com.android.ddmlib.TimeoutException e) {
e.printStackTrace();
}
if (rawScreen != null) {
Boolean landscape = false;
int width2 = landscape ? rawScreen.height : rawScreen.width;
int height2 = landscape ? rawScreen.width : rawScreen.height;
if (image == null) {
image = new BufferedImage(width2, height2,
BufferedImage.TYPE_INT_RGB);
} else {
if (image.getHeight() != height2 || image.getWidth() != width2) {
image = new BufferedImage(width2, height2,
BufferedImage.TYPE_INT_RGB);
}
}
int index = 0;
int indexInc = rawScreen.bpp >> 3;
for (int y = 0; y < rawScreen.height; y++) {
for (int x = 0; x < rawScreen.width; x++, index += indexInc) {
int value = rawScreen.getARGB(index);
if (landscape)
image.setRGB(y, rawScreen.width - x - 1, value);
else
image.setRGB(x, y, value);
}
}
try {
ImageIO.write((RenderedImage) image, "PNG", new File(filepath));
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
通过device对象,我们还可以安装、卸载应用:
try {
device.installPackage(path, true, args);
device.uninstallPackage(pakagename);
} catch (Exception e) {
e.printStackTrace();
}
还有很多方法可以调用:
getProperties()——获取系统属性
getBatteryLevel()——获取电池电量
getSerialNumber()——获取手机编号ID
isOnline()——获取手机是否在线
isOffline()——获取手机是否离线
…………