Alex

Android software development engineer

Welcome to my web site


Android截屏

目录

[TOC]

修改记录

版本 修改内容 日期
V1.0.0 初始版本 2022.3.8
     

System UI

Android系统层面提供了快捷键,可以实现快速截屏。比如,电源键+音量键实现快速截屏操作。

/**
 * 首先参考代码是Android 11 R48源码,系统提供的截屏API是SurfaceControl.screenshot
 * 
 * 函数原型:
 * public static Bitmap screenshot(Rect sourceCrop, int width, int height, int rotation);
 * 
 * 注意:
 * 1. 这是一个隐藏API,应用层无法直接访问,只能通过反射进行调用。
 * 2. 此API要求系统保护权限,只有系统应用才可以正常调用。
 *  <uses-permission android:name="android.permission.READ_FRAME_BUFFER"
 *      tools:ignore="ProtectedPermissions" />
 * 3. 此API存在不兼容性问题,不同的Android版本,System UI截屏API会变。
 */
public static Bitmap screenshot(Rect sourceCrop, int width, int height, int rotation) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
        String surfaceClassName = "android.view.SurfaceControl";
        try {
            Class<?> c = Class.forName(surfaceClassName);
            Method method = c.getMethod("screenshot", Rect.class, int.class, int.class, int.class);
            method.setAccessible(true);
            return (Bitmap) method.invoke(null, sourceCrop, width, height, rotation);
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException |ClassNotFoundException e) {
            e.printStackTrace();
            return  null;
        }
    } else {
        return null;
    }
}

应用层调用代码:

Display display = getApplicationContext().getDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getRealMetrics(displayMetrics);

/**
 * 屏幕宽度和高度
 */
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;

/**
 * display.getRotation() 获取屏幕旋转度
 * 
 * 返回值,截取的屏幕位图。
 */
Bitmap bitmap = Screenshot.screenshot(new Rect(0, 0, width, height), width, height,
        display.getRotation());

参考资料

https://blog.csdn.net/ccpat/article/details/45560851

https://www.jianshu.com/p/ca354e1adcde

http://wossoneri.github.io/2018/04/02/[Android]MediaProjection-Screenshot/

https://cloud.tencent.com/developer/article/1726618

https://www.yelcat.cc/index.php/archives/717/

https://blog.csdn.net/kong92917/article/details/50495740

https://github.com/goodbranch/ScreenCapture

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦