1.权限申明
<uses-permission android:name="android.permission.RECORD_AUDIO" />
2.请求录屏
private MediaProjectionManager mMediaProjectionManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding=DataBindingUtil.setContentView(this, R.layout.activity_main); mBinding.btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE); startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION); } }); }
3.判断录屏请求结果,然后将返回的数据给新创建的后台录屏服务
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_MEDIA_PROJECTION: if (resultCode == RESULT_OK && data != null) { RecordService.setResultData(data); startService(new Intent(getApplicationContext(), RecordService.class)); } break; } }
4.在录屏服务里开启一个线程并初始化ImageReader,MediaProjection,VirtualDisplay
private void initScreenCapture(){ mScreenDensity = ScreenUtils.getScreenDensityDpi(); mScreenWidth = ScreenUtils.getScreenWidth(); mScreenHeight = ScreenUtils.getScreenHeight(); mImageReader = ImageReader.newInstance(mScreenWidth, mScreenHeight, PixelFormat.RGBA_8888, 2); mMediaProjection =((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)) .getMediaProjection(Activity.RESULT_OK, mResultData); mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror", mScreenWidth, mScreenHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null); }
5.从ImageReader中获取最新屏幕图像并处理
private boolean getScreenCapture() { Image image = mImageReader.acquireLatestImage(); if (image!=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; if (mBitmap==null){ mBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888); } mBitmap.copyPixelsFromBuffer(buffer); image.close(); return true; } return false; }
6.最后记得释放VirtualDisplay,MediaProjection
@Override public void onDestroy() { super.onDestroy(); if (mVirtualDisplay == null) { return; } mVirtualDisplay.release(); mVirtualDisplay = null; if (mMediaProjection != null) { mMediaProjection.stop(); mMediaProjection = null; } }