一、使用MediaProjectionManager
Android5.0之后,开放截取屏幕的API,也就是利用MediaProjectionManager创建VirtualDisplay,传入与ImageReader关联的Surface,这样就可以从ImageReader中获取到Image,然后把Image的像素数组拷贝到Bitmap,如果要保存为图片,就用得到的Bitmap压缩为JPEG格式的图片。
首先是使用startActivityForResult发起录屏的请求:
private void startScreenShot(){
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
dpi = displayMetrics.densityDpi;
}
mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
if (mediaProjectionManager != null) {
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), 123);
}
}
在得到用户授权录屏后,在onActivityResult中获取MediaProjection-->VirtualDisplay-->ImagReader-->Image-->Bitmap:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
if (mediaProjection != null){
getBitmap(mediaProjection);
}
}
private void getBitmap(MediaProjection mediaProjection){
ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3);
mediaProjection.createVirtualDisplay("screen_shot",
width, height, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
imageReader.getSurface(), null, null);
imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireNextImage();
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);
String filePath = Environment.getExternalStorageDirectory().getPath() + "/hello.jpg";
//bitmap保存为图片
saveBitmap(bitmap, filePath);
image.close();
}
}, null);
}
private void saveBitmap(Bitmap bitmap, String filePath){
try {
FileOutputStream outputStream = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
优点:不用系统签名,不依赖系统底层API;
缺点:弹出确认框,需要用户授权录屏;
二、使用SurfaceControl
从上面分析可知,MediaProjectionManager录屏依赖Surface,分析Surface源码后,发现Surface其实是调用SurfaceControl,也就是说可以用SurfaceControl走捷径去截屏。其实系统框架层的截屏也是调用SurfaceControl。但是,由于SurfaceControl属于系统API,对用户不开放,我们无法直接调用。说到这里,大家应该都想到,用反射机制来调用。
正确的调用方式是这样的:
Bitmap bitmap = SurfaceControl.screenshot(width, height);
通过系统源码,可以知道它在Android.view.SurfaceControl路径下。既然路径、类、方法、参数都知道了,反射就没问题:
//使用反射调用截屏
private void screenShotByReflect(){
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
float[] dims = { mDisplayMetrics.widthPixels,
mDisplayMetrics.heightPixels };
try {
Class<?> demo = Class.forName("android.view.SurfaceControl");
Method method = demo.getDeclaredMethod("screenshot", int.class,int.class);
mScreenBitmap = (Bitmap) method.invoke(null,(int) dims[0],(int) dims[1]);
} catch (Exception e) {
e.printStackTrace();
}
}
在调用截屏之前,判断屏幕是否发生旋转:
private Bitmap takeScreenshot() {
mDisplay.getRealMetrics(mDisplayMetrics);
float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels};
float degrees = getDegreesForRotation(mDisplay.getRotation());
boolean requiresRotation = (degrees > 0);
//如果屏幕发生旋转,通过matrix旋转回来
if (requiresRotation) {
mDisplayMatrix.reset();
mDisplayMatrix.preRotate(-degrees);
mDisplayMatrix.mapPoints(dims);
dims[0] = Math.abs(dims[0]);
dims[1] = Math.abs(dims[1]);
}
//调用截屏
screenShotByReflect();
return mScreenBitmap;
}
优点:不用弹框授权,不用系统签名;
缺点:使用反射机制,如果系统API或者方法发生更改,导致无法调用;
三、使用screencap的adb命令
命令行是这样的:adb shell screencap -p file_path
在代码中执行,就不用adb shell,直接screencap -p file_path,调用Runtime的进程来执行:
public static void screenShotByShell(String filePath){
String shotCmd = "screencap -p " + filePath + " \n";
try {
Runtime.getRuntime().exec(shotCmd);
} catch (IOException e) {
e.printStackTrace();
}
}
优点:代码简单,直接获取到图片;
缺点:需要系统签名;
以上三种截屏方式,大家可以根据应用场景来使用。如果是用户app,需要连续录屏,建议采用MediaProjectionManager;如果是希望得到单个Bitmap,那么可以用SurfaceControl;如果是系统app,并且希望得到图片,首选screencap的adb命令行。