日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Android 截屏實(shí)現(xiàn)、屏幕截圖、MediaProjection、ImageReader

作者:break妖 更新時(shí)間: 2022-05-12 編程語言

1. 第一步:調(diào)起系統(tǒng)捕獲屏幕的Intent

MainActivity:

public void goCaptureIntent() {
    //第一步.調(diào)起系統(tǒng)捕獲屏幕的Intent
    mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
    startActivityForResult(captureIntent, SCREEN_SHOT_CODE);
}

2. 第二步:通過startForegroundService來獲取mediaProjection

注:sdk 28以及以下可以直接在Activity中獲取,29以及以上在Activity中獲取會(huì)報(bào)錯(cuò)

MainActivity:

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==SCREEN_SHOT_CODE && resultCode == RESULT_OK){
        //第二步通過startForegroundService來獲取mediaProjection
        Intent service = new Intent(this, ScreenShootService.class);
        service.putExtra("code", resultCode);
        service.putExtra("data", data);
        service.putExtra("width", getScreenWidth(this));
        service.putExtra("height", getScreenHeight(this));
        startForegroundService(service);
    }
}

3.?第三步:獲取mediaProjection

注:AndroidManifest.xml中注冊的service要加上以下屬性



?第三步的代碼:

ScreenShootService:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
        int resultCode = intent.getIntExtra("code", -1);
        Intent data = intent.getParcelableExtra("data");
        width = intent.getIntExtra("width",1080);
        height = intent.getIntExtra("height",1920);
        notification();
        //第三步:獲取mediaProjection
        MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
        if (mediaProjection == null) {
            Log.e(TAG, "media projection is null");
        }
        Bitmap bitmap = screenShot(mediaProjection);
        EventBus.getDefault().post(bitmap);
        return super.onStartCommand(intent, flags, startId);
}

?4.?第四步:通過mediaProjection截圖獲取Image

ScreenShootService:

//第四步;通過mediaProjection截圖獲取Image
public Bitmap screenShot(MediaProjection mediaProjection){
        Objects.requireNonNull(mediaProjection);
        @SuppressLint("WrongConstant")
        ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 60);
        VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay("screen", width, height, 1, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,imageReader.getSurface(), null, null);
        //取現(xiàn)在最新的圖片
        SystemClock.sleep(1000);
        //取最新的圖片
        Image image = imageReader.acquireLatestImage();
//        Image image = imageReader.acquireNextImage();
        //釋放 virtualDisplay,不釋放會(huì)報(bào)錯(cuò)
        virtualDisplay.release();
        return image2Bitmap(image);
}

5. 第五步:將Image轉(zhuǎn)為Bitmap

ScreenShootService:

//第五步:將Image轉(zhuǎn)為Bitmap
public static Bitmap image2Bitmap(Image image) {
        if (image == null) {
            System.out.println("image 為空");
            return null;
        }
        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 cutBitmap = Bitmap.createBitmap(bitmap,0,0,width/2,height/2);

        //壓縮圖片
//        Matrix matrix = new Matrix();
//        matrix.setScale(0.5F, 0.5F);
//        System.out.println(bitmap.isMutable());
//        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);

        image.close();
        return bitmap;
}

6.?第六步:展示截圖結(jié)果

這里是通過EventBust從Service傳到了Activity

MainActivity:

//接收service返回的bitmap圖片數(shù)據(jù)
@Subscribe(threadMode = ThreadMode.MAIN)//在ui線程執(zhí)行
public void onMoonEvent(Bitmap bitmap){
   //第六步:展示截圖結(jié)果
   imgShowImage.setBackground(new BitmapDrawable(bitmap));
}

異常處理1.?E/BufferQueueProducer: [ImageReader-2340x1080f1m1-24598-0](id:601600000001,api:1,p:1080,c:24598) dequeueBuffer: BufferQueue has been abandoned

分析:異常:BufferQueue已經(jīng)被丟棄了,還在使用

說明有在可能是截圖中使用到的某個(gè)對(duì)象被GC了,BufferQueue的對(duì)象大概有三個(gè)ImageReader 、VirtualDisplay 和 Image,Image在截圖萬之后已經(jīng)close掉了,然后嘗試截圖后分別對(duì)ImageReader和VirtualDisplay進(jìn)行釋放,ImageReader釋放問題依然存在,VirtualDisplay釋放解決了該問題。

VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay("screen", width, height, 1, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,imageReader.getSurface(), null, null);
...

使用完Image之后...
...

virtualDisplay.release();

?異常處理2:Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION

sdk版本產(chǎn)生的適配問題

兩種解決方案:

方案一:將sdk降低到28或者以下

?方案二:即需要使用 startForegroundService

也就是上面demo中使用到的方法

Activity:

public void goCaptureIntent() {
        //第一步.調(diào)起系統(tǒng)捕獲屏幕的Intent
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, SCREEN_SHOT_CODE);
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==SCREEN_SHOT_CODE && resultCode == RESULT_OK){
        //第二步通過startForegroundService來獲取mediaProjection
        Intent service = new Intent(this, ScreenShootService.class);
        service.putExtra("code", resultCode);
        service.putExtra("data", data);
        service.putExtra("width", getScreenWidth(this));
        service.putExtra("height", getScreenHeight(this));
        startForegroundService(service);
    }
}
Service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    int resultCode = intent.getIntExtra("code", -1);
    Intent data = intent.getParcelableExtra("data");
    width = intent.getIntExtra("width",1080);
    height = intent.getIntExtra("height",1920);
    notification();
    //第二步:創(chuàng)建mediaProjection
    MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
    if (mediaProjection == null) {
        Log.e(TAG, "media projection is null");
    }
    Bitmap bitmap = screenShot(mediaProjection);
    EventBus.getDefault().post(bitmap);
    return super.onStartCommand(intent, flags, startId);
}
AndroidManifest.xml:


?最終效果圖:

需要源碼的可以點(diǎn)個(gè)贊,點(diǎn)關(guān)注,然后評(píng)論里留下郵箱

原文鏈接:https://blog.csdn.net/qq_37980878/article/details/124698652

欄目分類
最近更新