Capture screenshot in Java (AWT)

In Java there is a easy was to capture screenshots. The following captureScreenshot method will capture a screenshot of the display of your screen and save it to the disk.

If you want to create a screenshot of a specific part of your screen, you have to modyfy the rectangle. You can do this with rectangle .setBounds(int x, int y, int width, int height).

Rectangle API: http://docs.oracle.com/

Note: This will need “java.awt”. So you cannot run this code on Android devices, because there is no java.awt package available. Also note, that you have to run a X-Server on linux to execute this. If you try to execute this on a linux server without X-Server, you will not be able to capture screenshot of your terminal.
On Windows this is not a problem. The capture screenshot method will work on windows even if you are not the Administrator.

How to disable Screenshot in Android

Sometimes it can happen, that the app has to prevent android from taking a screenshot of the app. This can make sense if the app is being pushed into the background and/or for security reasons. So use FLAG_SECURE:

This line secures against manual screenshots and automatic screenshots from the ICS recent-tasks history. You still see the application name and icon, but the screenshot is black.

Note: On some android devices FLAG_SECURE can be problematic: Sometimes FLAG_SECURE causes animation problems in screen rotation animation. See code.google.com/p/android/issues/detail?id=58632 – this has been fixed on Android 4.4.