如何在不root的情况下包含截图功能phone?

How to include screenshot function without rooting phone?

我是 android 函数和库功能的新手,因此我想问一下是否有任何其他方法可以在我的应用程序中包含屏幕截图功能而无需 root 我的 phone?

我在这里阅读的几乎所有文章都只会导致 phone root 以便应用屏幕截图功能。但是,我在这些文章中放置了一个代码答案,但由于我的 phone 没有 root,所以只返回了一张黑色图像。我猜。

有没有其他方法或者我现在应该开始 root 我的 phone 吗?

您不需要库或 root 来获取您自己的应用程序的屏幕截图,因为该应用程序可以访问它自己的所有 Views。我们只需要获取 ActivityDecorView,并通过 Canvas 将其绘制到 Bitmap。以下方法包含一个 boolean cropStatusBar 参数以适应沉浸式模式捕获。

public static Bitmap getActivityScreenshot(Activity activity, boolean cropStatusBar) {
    int statusBarHeight = 0;

    if (cropStatusBar) {
        int resId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        statusBarHeight = activity.getResources().getDimensionPixelSize(resId);
    }

    View decor = activity.getWindow().getDecorView();
    Bitmap result = Bitmap.createBitmap(decor.getWidth(),
                                        decor.getHeight() - statusBarHeight,
                                        Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(result);

    decor.setDrawingCacheEnabled(true);
    Bitmap bmp = decor.getDrawingCache();
    Rect src = new Rect(0, statusBarHeight, bmp.getWidth(), bmp.getHeight());
    Rect dst = new Rect(0, 0, result.getWidth(), result.getHeight());
    c.drawBitmap(bmp, src, dst, null);
    decor.setDrawingCacheEnabled(false);

    return result;
}