I am currently developing an application for Android and wanted to know how to detect a screenshot. I tried with FileObserver but the problem is that all events are detected ( when device goes into sleep, message, etc. ) . How to detect only screenshot ?
Thank you in advance !
You can create FileObserver that only monitors screenshot directory plus only trigger events for file or directory creation. For more information click here.
I have improve the code from alijandro's comment to make it easy-to-use class and fix the problem when content observer has detect the image from camera (should be screenshot image only). Then wrap it to delegate class for convenient to use.
• ScreenshotDetectionDelegate.java
• ScreenshotDetectionActivity.java
• MainActivity.java
How did you use
FileObserver
to detect screen shot creation? When usingFileObserver
, only monitor the file creation event in screen shot directory.Don't forget to declare corresponding permissions to access content in SD card.
Another solution to detect the screen shot is using
ContentObserver
, because there will be a record inserted to the system media database after screen shot. Following is the code snippet usingContentObserver
to monitor the event. By usingContentObserver
, it's not necessary to declarewrite/read external storage
permissions, but you have to do some filters on the file name to make sure it's a screen shot event.Updated
If you use second method, you have to request
READ_EXTERNAL_STORAGE
after version Android M, otherwise it will throwSecurityException
. For more information how to request runtime permission, refer here.I made the git project for android screenshot.
I used Content Observer.
working fine from API 14 to Recent Version
You can check here
1.ScreenShotContentObserver .class
(original screenshot delete -> inform screenshot taken and give screenshot bitmap )
Util.class