直播項目中,截取目前的視訊手機畫面分享主播,支援android5.0以上手機。
調用方法,其中mRl是布局父控件,
private String TAG = "TAG";
private MediaProjection mediaProjection;
MediaProjectionManager projectionManager;
private VirtualDisplay virtualDisplay;
private int mResultCode;
private Intent mData;
private ImageReader imageReader;
private int width;
private int height;
private int dpi;
private String imageName;
private Bitmap bitmap;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void capture() {
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
width = metric.widthPixels;
height = metric.heightPixels;
dpi = metric.densityDpi;
projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
StartScreenShot(mRl);
}/**
* 調用截屏方法
*
* @param view 需要截取的視圖
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void StartScreenShot(View view) {
startActivityForResult(projectionManager.createScreenCaptureIntent(),
SCREEN_SHOT);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SCREEN_SHOT) {
if (resultCode == RESULT_OK) {
mResultCode = resultCode;
mData = data;
setUpMediaProjection();
setUpVirtualDisplay();
startCapture();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setUpVirtualDisplay() {
imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 1);
mediaProjection.createVirtualDisplay("ScreenShout",
width, height, dpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
imageReader.getSurface(), null, null);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setUpMediaProjection() {
mediaProjection = projectionManager.getMediaProjection(mResultCode, mData);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void startCapture() {
SystemClock.sleep(1000);
imageName = System.currentTimeMillis() + ".png";
Image image = imageReader.acquireNextImage();
if (image == null) {
Log.e(TAG, "image is null.");
return;
}
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
image.close();
if (bitmap != null) {
//獲得圖檔資源
}
}