废话不多说 直接上代码(使用kotlin编写大致与java差不多) 代码注释也挺详细的
利用mediaProjection 实现截屏与录屏
mediaProjection 是android 5.0 加入的一个 主要用户捕捉屏幕的东西
createVirtualDisplay(String name, int width, int height, int dpi, int flags, Surface surface, VirtualDisplay.Callback callback, Handler handler)
//创建一个VirtualDisplay捕获屏幕的内容。
//捕捉到的内容将写入到传入的surface中
//因此可将传入MediaRecorder以及ImageReader中的surface 并 通过他们取出surface进行截图与录制
class ScreenCapture constructor(private val width : Int ,private val height : Int ){
private var mImageReader : ImageReader = ImageReader.newInstance(width,height, PixelFormat.RGBA_8888,3)
private var mediaProjectionManager = App.app.mediaProjectionManager
//初始化截图功能
fun startCapture(resultCode : Int, data : Intent?) {
val mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data)
mediaProjection.createVirtualDisplay("capture",width,height,1,
DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
mImageReader.surface,null,null)
}
fun acquire() : Bitmap?{
var image: Image? = null
//当未开始录制的时候先调用此方法会报错
//java.lang.IllegalStateException: mImageReader.acquireLatestImage() must not be null