【问题标题】:Unable to take snapshot of launched app programatically. Getting mDrawingCache as NULL无法以编程方式拍摄已启动应用的快照。将 mDrawingCache 设为 NULL
【发布时间】:2026-02-05 11:40:01
【问题描述】:

我可以通过以下代码拍摄 Hello World 应用程序的快照。'

private void takeScreenshot() 
``{
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);

            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or OOM
            e.printStackTrace();
        }
    }

我已经使用 Intent(getLaunchIntent 用于包方法)启动了另一个应用程序(excel)。现在我想截取启动的应用程序的屏幕截图。我尝试调用与上面相同的方法并将视图更改如下:

查看 v1 = findViewByID(android.R.id.content);

但是当我尝试通过 位图 cac = v1.getDrawingCache()

我将 cac 设为 NULL。如何检索已启动应用的视图以使 getDrawingCache 不返回 NULL?

【问题讨论】:

    标签: android


    【解决方案1】:

    如何检索已启动应用的视图

    出于明显的隐私和安全原因,您不能这样做。

    欢迎您在 Android 5.0+ 上使用媒体投影 API 截屏,并获得用户许可。

    【讨论】:

    • @McflyDroid:仅来自您的开发机器。
    • 谢谢,我可以用 uiautomator 做到这一点
    最近更新 更多