Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take screenshot of current showing screen, NOT the current activity

I'm trying to make a little Android app that triggers a screenshot capture of the current showing screen when a specific notification appears. For example, I'm on whatsapp and a Whatsapp notification appears -> That triggers a whatsapp capture.

Well, my current code actually detects notifications and triggers a screenshot when a notification comes, but not the way I want. I get a screenshot of my MainActivity, even if it's not showing on the screen. I just want to screenshot what it's appearing on the screen. It seems easy but I'm not being able to do it!

I leave my current NotificationReceiver class, which is failing because it captures the MainActivity and not the screen:

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
    }
}

Any ideas of how can I proceed? I'm actually stuck. Help would be really appreciated!

like image 862
Markomso Avatar asked Sep 01 '25 16:09

Markomso


1 Answers

You would need to use the media projection APIs on Android 5.0+, and set your minSdkVersion to 21. For privacy and security reasons, apps cannot take screenshots of other apps without explicit user permission, and that only became possible with Android 5.0.

This sample app demonstrates taking screenshots on demand.

like image 83
CommonsWare Avatar answered Sep 04 '25 07:09

CommonsWare