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

时间:2016-10-27 19:27:34

标签: android screenshot

我正在尝试创建一个小型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 个答案:

答案 0 :(得分:5)

您需要在Android 5.0+上使用the media projection APIs,并将minSdkVersion设置为21.出于隐私和安全原因,如果没有明确的用户许可,应用无法截取其他应用的屏幕截图使用Android 5.0成为可能。

This sample app演示了根据需要截取屏幕截图。

相关问题