android API 21 以上截图

Author Avatar ZTFtrue 发表于 • 2018年03月30日 10:54 • 共 • 253 • 次浏览

android 5.0 以上开放了截图,5.0以下的需要root权限。

主要用到的三个系统工具(全局变量)

        private MediaProjection mMediaProjection;
        private ImageReader mImageReader;
        MediaProjectionManager mediaProjectionManager;
        private VirtualDisplay mVirtualDisplay;
        Intent mResultData;//请求权限返回的数据

开始:

  1. 请求权限
   requestCapturePermission();//开始
   @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void requestCapturePermission() {
        mediaProjectionManager = (MediaProjectionManager)
                getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(
                mediaProjectionManager.createScreenCaptureIntent(),
                10);
        mImageReader = ImageReader.newInstance(1080, 1920, 
        PixelFormat.RGBA_8888, 2);
    }
  1. 收到权限
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10:
                if (resultCode == RESULT_OK && data != null) {
                    mResultData = data;
                    photo();//开始
                }
                break;
        }
    }
  1. 开始获取屏幕内容
 public void photo() {
        // 延时以避免 mImageReader.acquireLatestImage() 返回 null
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                //获取当前屏幕内容
                startVirtual();
            }
        }, 5);
        handler.postDelayed(new Runnable() {
            public void run() {
                //生成图片保存到本地
                startCapture();

            }
        }, 30);
    }
  public void startVirtual() {
        if (mMediaProjection != null) {
            virtualDisplay();
        } else {
            //mResultData是在Activity中用户授权后返回的结果
            mMediaProjection = mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, mResultData);
            virtualDisplay();
        }
    }

    private void startCapture() {

        Image image = mImageReader.acquireLatestImage();

        if (image == null) {
            photo();
        } else {
            saveImage(image);
        }
    }
   private void virtualDisplay() {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager WindowManager = (WindowManager) getApplication()
                .getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = WindowManager.getDefaultDisplay();
        defaultDisplay.getMetrics(metrics);
        int mScreenDensity = metrics.densityDpi;
        int mDisplayWidth = defaultDisplay.getWidth();
        int mDisplayHeight = defaultDisplay.getHeight();
         mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                mDisplayWidth, mDisplayHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(), null, null);
    }
  1. 存储图片
  protected void doInBackground(Image... params) {
        if (params == null || params.length < 1 || params[0] == null) {

            return;
        }
        Image image = params[0];
        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 = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        image.close();
        File fileImage = null;
        if (bitmap != null) {
            try {
                fileImage = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".png");
                if (!fileImage.exists()) {
                    fileImage.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(fileImage);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(fileImage);
                media.setData(contentUri);
                sendBroadcast(media);
            } catch (IOException e) {
                e.printStackTrace();
                fileImage = null;
            }
        }
    }
  1. 关闭
 // 服务或活动消耗时关闭
    private void stopVirtual() {
        if (mVirtualDisplay == null) {
            return;
        }
        mVirtualDisplay.release();
        mVirtualDisplay = null;
    }

请自行决定变量 全局、局部、私有等。

最后编辑于 • 2018年03月30日 10:54 •  

你尚未登录,无法进行回复。