前言

记录一下,Android截图方法和保存。

  1. 我这是系统应用测试,非系统应用需要权限的申请等
  2. Android P验证OK

正文

获取截图

public static Bitmap getScreenShot() {
    try {
        //反射 SurfaceControl screenshot()被隐藏
        String surfaceClassName = "android.view.SurfaceControl";
        @SuppressLint("PrivateApi")
        Class<?> clazz = Class.forName(surfaceClassName);
        @SuppressLint("DiscouragedPrivateApi")
        Method screenshot = clazz.getDeclaredMethod("screenshot", Rect.class, int.class, int.class, int.class);
        screenshot.setAccessible(true);
        return (Bitmap) (screenshot.invoke(clazz, new Rect(0, 0, CaptureUtils.getScreenWidth(), CaptureUtils.getScreenHeight()),
                CaptureUtils.getScreenWidth(), CaptureUtils.getScreenHeight(), 0));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

CaptureUtils.getScreenWidth()和CaptureUtils.getScreenHeight()屏幕的高度
。如果是Activity中,可以用

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(dm);

如果是Service中,需要借助其他方式获取。

保存截图

private static final String mDiskPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "BiuCapture";
public static String saveBitmap(Bitmap bitmap) {
    String path = mDiskPath + File.separator + SystemClock.uptimeMillis() + ".png";
    Log.d(CaptureApp.TAG, "saveBitmap path : " + path);
    FileOutputStream fileOutputStream = null;
    try {
        File file = new File(mDiskPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(path);
        if (!file.exists()) {
            Log.d(CaptureApp.TAG, "saveBitmap createNewFile : " + file.createNewFile());
        }
        fileOutputStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.flush();
        return path;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != fileOutputStream) {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

参考文章

  1. SurfaceControl.screenshot()用法 | SurfaceControl.screenshot()使用后返回null的解决方案
  2. Android屏幕截屏(全屏bitmap)
  3. DisplayMetrics获取宽高不对

相关文章

暂无评论

none
暂无评论...