Image image = imageReader.acquireNextImage();
截屏时这句话报空指针(为什么我总和空指针杠上),原因是:读取截屏数据,对象的创建完成需要一定的时间,从创建对象到图片数据真正可用需要在OnImageAvailableListener的回调方法中完成
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader mImageReader) {
Image image = null;
try {
image = mImageReader.acquireLatestImage();
if (image != null) {
final Image.Plane[] planes = image.getPlanes();
if (planes.length > 0) {
final ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
// create bitmap
Bitmap bmp = Bitmap.createBitmap(mWidth + rowPadding / pixelStride,
mHeight, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buffer);
Bitmap croppedBitmap = Bitmap.createBitmap(bmp, 0, 0, mWidth, mHeight);
saveBitmap(croppedBitmap);//保存图片
if (croppedBitmap != null) {
croppedBitmap.recycle();
}
if (bmp != null) {
bmp.recycle();
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
if (mImageReader != null) {
mImageReader.close();
}
if (display != null) {
display.release();
}
mImageReader.setOnImageAvailableListener(null, null);
mProjection.stop();
onScreenshotTaskOver();
}
}
}, getBackgroundHandler());
是的好多地方都没有给出 getBackgroundHandler 这个 handler 的使用方式,于是在参考网址【1】中扒了作者的源代码下来:
//在后台线程里保存文件
Handler backgroundHandler;
private Handler getBackgroundHandler() {
if (backgroundHandler == null) {
HandlerThread backgroundThread =
new HandlerThread("catwindow", android.os.Process
.THREAD_PRIORITY_BACKGROUND);
backgroundThread.start();
backgroundHandler = new Handler(backgroundThread.getLooper());
}
return backgroundHandler;
}
格式什么的以后再说咯
参考:1、http://www.tk4479.net/SpringIOC/article/details/78568438
2、https://github.com/miqt/CapWindow