如何使用 Lollipop 以编程方式捕获屏幕截图

How to capture a screenshot programmatically with Lollipop

Media Projection 软件包是新的 Lollipop,它允许应用程序实时捕获设备屏幕以流式传输到视频。我希望这也可以用于捕获单个静态屏幕截图,但到目前为止我还没有成功。当然,捕获的视频的第一帧可以工作,但我的目标是与设备的像素分辨率相匹配的完美无损屏幕截图。捕获的视频中的静止图像无法提供这一点。

我尝试了很多方法,但我最接近的解决方案是首先启动 invisible activity. This activity then follows the API example for starting screen capture, which can include asking the user's permission. Once screen capture is enabled, the screen image is live in a SurfaceView. However, I cannot find a way to capture a bitmap from the SurfaceView. There are lots of questions and discussions about this, but no solutions seem to work, and there is some evidence that it is impossible

有什么想法吗?

您无法捕获 SurfaceView 的内容。

您可以将 SurfaceView 替换为具有进程内消费者的 Surface 对象,例如 SurfaceTexture. In the android-ScreenCapture example linked from the question, mMediaProjection.createVirtualDisplay() wants a Surface to send images to. If you create a SurfaceTexture, and use that to construct a Surface,MediaProjection 生成的图像将可从 OpenGL ES 纹理获得。

如果您不喜欢 GLES,可以使用 ImageReader class。它还提供了一个可以传递给 createVirtualDisplay() 的 Surface,但是从软件访问像素更容易。