如何截取屏幕截图?

how to capture a screenshot?

我知道关于截屏的问题很多,我已经查了大部分。他们有相同的答案(代码变化很小)。

我有以下截图方法:

@NonNull
public static Bitmap takeScreenShot(Window window) throws IOException {
    final View rootView = window.getDecorView().getRootView();
    final boolean drawingCacheEnabled = rootView.isDrawingCacheEnabled();
    rootView.setDrawingCacheEnabled(true);

    try {
        return Bitmap.createBitmap(rootView.getDrawingCache());
    } finally {
        rootView.setDrawingCacheEnabled(drawingCacheEnabled);
    }
}

您可以像这样使用它:takeScreenShot(getActivity().getWindow())

但是这些方法有几个局限性:

  1. 如果屏幕上有一些对话,它们将不会被捕获 截屏。
  2. 它可以与硬件加速视图一起使用吗?根据 文档:

    When hardware acceleration is turned on, enabling the
    drawing cache has no effect on rendering because the system uses a
    different mechanism for acceleration which ignores the flag

  3. 屏幕截图包含黑框 而不是 GLviews。 (例如,当您的应用程序有地图时。)。这似乎是第二点的结果。

所以我的问题是,有没有可以解决至少部分问题的无需root 的解决方案?

查看以下 GitHub 回购(不是我的!):https://github.com/AndroidDeveloperLB/ScreenshotSample

此外,以下内容将对您有所帮助: