当前屏幕截图,而不是当前活动的截图。

4
我正在尝试制作一个小型的Android应用程序,当特定通知出现时触发当前显示屏幕的截图捕获。例如,我在使用Whatsapp,然后Whatsapp通知出现->这会触发Whatsapp的截图。

目前我的代码可以检测通知并在通知出现时触发截图,但不是我想要的方式。我得到的是MainActivity的截图,即使它没有显示在屏幕上。我只想截屏当前屏幕上正在显示的内容。这似乎很容易,但我无法做到!

我留下了我的当前NotificationReceiver类,因为它捕获了MainActivity而不是屏幕:

class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String temp = intent.getStringExtra("notification_event") + "\n" + txtView.getText();
        txtView.setText(temp);

        if (intent.getStringExtra("notification_event").contains("bet")) {
            Log.i("Dentro", "dentro");

            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();
            } catch (Throwable e) {
                // Several error may come out with file handling or OOM
                Log.i("Catch","Error dentro del if(contains)");
                e.printStackTrace();
            }
        }//fin if
    }
}

有什么办法可以帮我继续进行吗?我现在卡住了。非常感谢你的帮助!

1个回答

6

如果您想在Android 5.0+上截屏,您需要使用媒体投影API,并将minSdkVersion设置为21。出于隐私和安全原因,应用程序无法在未经用户明确许可的情况下截取其他应用程序的屏幕截图,这仅在Android 5.0之后才有可能。

此示例应用程序演示了如何按需截屏。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接