Android 截图工具类

作者: 大大大寒 | 来源:发表于2018-06-26 16:52 被阅读23次

    使用方式

    mMediaProjection获取方式

    mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), 1);
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            mResultCode = resultCode;
            mResultData = data;
            mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData);
        }
    
    
    
    view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Log.i(TAG, "view.setOnLongClickListener");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            captureUtil = new CaptureUtil().setUpMediaProjection(mContext, mMediaProjection);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        captureUtil.startCapture();
                                    } catch (NullPointerException r) {
                                        r.printStackTrace();
                                    }
                                }
                            }, 500);
                        }
                    }, 500);
                    return false;
                }
            }
    
    public class CaptureUtil {
        private static final String TAG = "CaptureUtil";
    
        private SimpleDateFormat dateFormat = null;
        private String strDate = null;
        private String pathImage = null;
        private String nameImage = null;
        private ImageReader mImageReader = null;
    
        private MediaProjection mMediaProjection = null;
        private VirtualDisplay mVirtualDisplay = null;
    
        private int windowWidth = 0;
        private int windowHeight = 0;
        private int mScreenDensity = 0;
    
        private DisplayMetrics metrics = null;
        private WindowManager mWindowManager = null;
        Context context;
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public CaptureUtil setUpMediaProjection(Context context, MediaProjection mediaProjection) {
            if (mediaProjection == null) {
                Log.i(TAG, "MediaProjection null");
                return null;
            }
            this.context = context;
            mMediaProjection = mediaProjection;
            createVirtualEnvironment();
            virtualDisplay();
            return CaptureUtil.this;
        }
    
        private void createVirtualEnvironment() {
            dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
            strDate = dateFormat.format(new java.util.Date());
            Log.i(TAG, "pathImage : " + MApplication.getApplication().getExternalCacheDir().getPath() + "/Pictures/");
            pathImage = MApplication.getApplication().getExternalCacheDir().getPath() + "/Pictures/";
            nameImage = pathImage + strDate + ".png";
            mWindowManager = (WindowManager) MApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
            windowWidth = mWindowManager.getDefaultDisplay().getWidth();
            windowHeight = mWindowManager.getDefaultDisplay().getHeight();
            metrics = new DisplayMetrics();
            mWindowManager.getDefaultDisplay().getMetrics(metrics);
            mScreenDensity = metrics.densityDpi;
            mImageReader = ImageReader.newInstance(windowWidth, windowHeight, 0x1, 2); //ImageFormat.RGB_565
            if (mImageReader == null) {
                Log.i(TAG, "ImageReader.newInstance null");
            }
            Log.i(TAG, "prepared the virtual environment");
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private void virtualDisplay() {
            mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
                    windowWidth, windowHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                    mImageReader.getSurface(), null, null);
            Log.i(TAG, "virtual displayed");
        }
    
    
        //ImageReader.newInstance 不能直接调用acquireLatestImage.可能会出现null 需要加一定延迟
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public Bitmap startCaptureBitmap() throws NullPointerException {
            return startCaptureBitmap(0, 0, 0, 0);
        }
    
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public Bitmap startCaptureBitmap(int x, int y, int mWidth, int mHeight) throws NullPointerException {
            strDate = dateFormat.format(new java.util.Date());
            nameImage = pathImage + strDate + ".png";
            Image image = mImageReader.acquireLatestImage();
            long startTime = System.currentTimeMillis();
            int num = 0;
            //最好先创建captureUtil 示例 300ms后 在调用否则可能检查为空
            if (image == null) {
                for (; ; ) {
                    image = mImageReader.acquireLatestImage();
                    num++;
                    if (image != null || num > 30000)
                        break;
                }
    
            }
            long endTime = System.currentTimeMillis();
            Log.e(TAG, endTime - startTime + "  time  num :" + num);
            int width = 0;
            int height = 0;
            if (mWidth == 0 || mHeight == 0) {
                width = image.getWidth();
                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, x<0?x:0, y<0?y:0, width, height);
            image.close();
            Log.i(TAG, "image data captured");
            return bitmap;
        }
    
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public File startCapture() throws NullPointerException {
            Bitmap bitmap = startCaptureBitmap();
            return startCapture(bitmap);
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public File startCapture(Bitmap bitmap) throws NullPointerException {
            File fileImage = null;
            if (bitmap != null) {
                try {
                    fileImage = new File(nameImage);
                    if(fileImage.getParentFile().exists()||fileImage.getParentFile().mkdirs()){
                        if (!fileImage.exists()) {
                            fileImage.createNewFile();
                            Log.i(TAG, "image file created");
                        }
                    }else {
                        return null;
                    }
    
    
                    FileOutputStream out = new FileOutputStream(fileImage);
                    if (out != null) {
                        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);
                        context.sendBroadcast(media);
                        Log.i(TAG, "screen image saved");
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return fileImage;
        }
    
    
    }
    

    相关文章

      网友评论

        本文标题:Android 截图工具类

        本文链接:https://www.haomeiwen.com/subject/argosftx.html