前言

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

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

正文

获取截图

  1. public static Bitmap getScreenShot() {
  2. try {
  3. //反射 SurfaceControl screenshot()被隐藏
  4. String surfaceClassName = "android.view.SurfaceControl";
  5. @SuppressLint("PrivateApi")
  6. Class<?> clazz = Class.forName(surfaceClassName);
  7. @SuppressLint("DiscouragedPrivateApi")
  8. Method screenshot = clazz.getDeclaredMethod("screenshot", Rect.class, int.class, int.class, int.class);
  9. screenshot.setAccessible(true);
  10. return (Bitmap) (screenshot.invoke(clazz, new Rect(0, 0, CaptureUtils.getScreenWidth(), CaptureUtils.getScreenHeight()),
  11. CaptureUtils.getScreenWidth(), CaptureUtils.getScreenHeight(), 0));
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. return null;
  16. }
复制

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

  1. DisplayMetrics dm = new DisplayMetrics();
  2. getWindowManager().getDefaultDisplay().getRealMetrics(dm);
复制

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

保存截图

  1. private static final String mDiskPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "BiuCapture";
复制
  1. public static String saveBitmap(Bitmap bitmap) {
  2. String path = mDiskPath + File.separator + SystemClock.uptimeMillis() + ".png";
  3. Log.d(CaptureApp.TAG, "saveBitmap path : " + path);
  4. FileOutputStream fileOutputStream = null;
  5. try {
  6. File file = new File(mDiskPath);
  7. if (!file.exists()) {
  8. file.mkdirs();
  9. }
  10. file = new File(path);
  11. if (!file.exists()) {
  12. Log.d(CaptureApp.TAG, "saveBitmap createNewFile : " + file.createNewFile());
  13. }
  14. fileOutputStream = new FileOutputStream(file);
  15. bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
  16. fileOutputStream.flush();
  17. return path;
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. } finally {
  21. if (null != fileOutputStream) {
  22. try {
  23. fileOutputStream.close();
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. return null;
  30. }
复制

参考文章

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

相关文章

暂无评论

none
暂无评论...