Android 5.0 螢幕錄製/截圖

月光邊境發表於2018-01-24

Android 5.0之後的新API,平時很少用到這裡記錄下

1. 獲取系統服務

        mMediaProjectionManager = (MediaProjectionManager) getSystemService(
                Context.MEDIA_PROJECTION_SERVICE);
        if (mMediaProjectionManager != null) {
            startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(),
                    200);
        }
複製程式碼

2. onActivityResult中獲取MediaProjection

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
        }
    }
複製程式碼

3.開始錄製

    private void startCapture() {
        mMediaProjection.createVirtualDisplay(
                "screen-mirror",
                mSurfaceView.getWidth(),
                mSurfaceView.getHeight(),
                Resources.getSystem().getDisplayMetrics().densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mSurfaceView.getHolder().getSurface(),
                null,
                null);
    }
複製程式碼

4.截圖

  1. 如果取餘截圖的話我們要使用到ImageReader這個類,呼叫createVirtualDisplay:
    private void startCapture() {
        mImageReader = ImageReader.newInstance(mWindowWidth, mWindowHeight,
                PixelFormat.RGBA_8888, 2);
        mMediaProjection.createVirtualDisplay(
                "screen-mirror",
                mWindowWidth,
                mWindowHeight,
                mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(),
                null,
                null);
    }
複製程式碼
  1. 擷取Bitmap
    private Bitmap screenshot() {
        Image image = mImageReader.acquireLatestImage();
        int width = image.getWidth();
        int height = image.getHeight();
        Image.Plane[] planes = image.getPlanes();
        ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();
        int rowPadding = rowStride - pixelStride * width
        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride,
                height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        image.close();
        return bitmap;
    }
複製程式碼

相關文章