截取当前显示屏幕的屏幕截图,而不是当前活动

Mar*_*mso 2 android screenshot

我正在尝试创建一个小应用程序,当出现特定通知时触发当前显示屏幕的屏幕截图.例如,我正在使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

有关如何进行的任何想法?我其实被卡住了.帮助将非常感谢!

Com*_*are 5

您需要在Android 5.0+上使用媒体投影API,并将您设置minSdkVersion为21.出于隐私和安全原因,如果没有明确的用户许可,应用无法截取其他应用的屏幕截图,而这只能通过Android 5.0实现.

此示例应用程序演示了按需截屏.