1. 第一步:调起系统捕获屏幕的Intent
MainActivity:public void goCaptureIntent() {//第一步.调起系统捕获屏幕的IntentmMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();startActivityForResult(captureIntent, SCREEN_SHOT_CODE);}
2. 第二步:通过startForegroundService来获取mediaProjection
注:sdk 28以及以下可以直接在Activity中获取,29以及以上在Activity中获取会报错
MainActivity:@RequiresApi(api = Build.VERSION_CODES.O)@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if(requestCode==SCREEN_SHOT_CODE && resultCode == RESULT_OK){//第二步通过startForegroundService来获取mediaProjectionIntent 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要加上以下属性
<service android:name=".ScreenShootService"android:enabled="true"android:foregroundServiceType="mediaProjection"></service>
第三步的代码:
ScreenShootService:@Overridepublic 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();//第三步:获取mediaProjectionMediaProjectionManager 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截图获取Imagepublic 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);//取现在最新的图片SystemClock.sleep(1000);//取最新的图片Image image = imageReader.acquireLatestImage();// Image image = imageReader.acquireNextImage();//释放 virtualDisplay,不释放会报错virtualDisplay.release();return image2Bitmap(image);}
5. 第五步:将Image转为Bitmap
ScreenShootService://第五步:将Image转为Bitmappublic 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.第六步:展示截图结果
这里是通过EventBust从Service传到了Activity
MainActivity://接收service返回的bitmap图片数据@Subscribe(threadMode = ThreadMode.MAIN)//在ui线程执行public void onMoonEvent(Bitmap bitmap){//第六步:展示截图结果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已经被丢弃了,还在使用
说明有在可能是截图中使用到的某个对象被GC了,BufferQueue的对象大概有三个ImageReader 、VirtualDisplay 和 Image,Image在截图万之后已经close掉了,然后尝试截图后分别对ImageReader和VirtualDisplay进行释放,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版本产生的适配问题
两种解决方案:
方案一:将sdk降低到28或者以下
方案二:即需要使用 startForegroundService
也就是上面demo中使用到的方法
Activity:public void goCaptureIntent() {//第一步.调起系统捕获屏幕的IntentmMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();startActivityForResult(captureIntent, SCREEN_SHOT_CODE);}@RequiresApi(api = Build.VERSION_CODES.O)@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if(requestCode==SCREEN_SHOT_CODE && resultCode == RESULT_OK){//第二步通过startForegroundService来获取mediaProjectionIntent 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:@Overridepublic 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();//第二步:创建mediaProjectionMediaProjectionManager 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:<service android:name=".ScreenShootService"android:enabled="true"android:foregroundServiceType="mediaProjection">
最终效果图: