我正在尝试使用 MediaProjection API 和 ImageReader 来捕获模拟器屏幕。但它总是产生黑屏。代码如下。
@Override
public void onImageAvailable(ImageReader reader) {
Log.i(TAG, "in OnImageAvailable");
FileOutputStream fos = null;
Bitmap bitmap = null;
Image img = null;
try {
img = reader.acquireLatestImage();
if (img != null) {
Image.Plane[] planes = img.getPlanes();
if (planes[0].getBuffer() == null) {
return;
}
int width = img.getWidth();
int height = img.getHeight();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
Log.v(TAG, "width: "+width+", height: "+height+", pixelStride: "+pixelStride+", rowStride: "+rowStride+", rowPadding: "+rowPadding);
int offset = 0;
bitmap = Bitmap.createBitmap(metrics, width, height, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = planes[0].getBuffer();
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int pixel = 0;
pixel |= (buffer.get(offset) & 0xff) << 16; // R
pixel |= (buffer.get(offset + 1) & 0xff) << 8; // G
pixel |= (buffer.get(offset + 2) & 0xff); // B
pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A
bitmap.setPixel(j, i, pixel);
offset += pixelStride;
}
offset += rowPadding;
}
String name = "/pyscreen" + count + ".png";
count++;
File file = new File(Environment.getExternalStorageDirectory(), name);
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.i(TAG, "image saved in" + Environment.getExternalStorageDirectory() + name);
img.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bitmap) {
bitmap.recycle();
}
if (null != img) {
img.close();
}
}
}
我已经提到Take a screenshot using MediaProjection and Android ImageReader.acquireLatestImage return invalid JPG \ reader-acquirelatestimage-returns-invalid-jpg 它们适用于真实设备,但不适用于模拟器。
如何使用模拟器进行屏幕截图?我的实现有问题吗?你有什么想法?
感谢所有帮助!