Snapchat has a functionality that is to notify the user every time someone, any other user, takes a screenshot of their stories.
At first I thought about the possibility of checking if the user pressed Volume Down+ Power, but nothing guarantees that the screenshot will be saved, since there may not be enough memory to save. Also, I think that each device can change the way how to capture the screen, not to mention that there are other applications that facilitate this process.
Another way would be to check if there have been any changes to the Screenshots directory, using the class FileObserver
, but there is also no guarantee that this path will be the same on all devices.
How can I check if the user took a screenshot at the time of using the app?
As you mentioned in your question when using
FileObserver
No guarantees that on all devices that path will be the same.The Android API does not have a fixed route for screenshots, but
It could work. That's what ICS uses as a route.
So what I can think of to do then is create a list of paths for each device and bind them with Build .
When using FileObserver , only monitor the file creation event on the screenshot directory.
Don't forget to declare the corresponding permissions to access the content on the SD card.
Another solution to detect the screenshot is to use
ContentObserver
, because there will be a record inserted in the system media database after the screenshot. The following is the code snippet used to monitor the eventContentObserver
. When using , you don't need to declare the /ContentObserver
permissions , but you do need to do some filtering on the filename to make sure it's a screenshot event.write
read
external storage
If you use this method, you must request
READ_EXTERNAL_STORAGE
after the version ofAndroid M
, otherwise it will returnSecurityException
. For more information on: How to request runtime permission, see here .However this has a problem that when the content watcher has detected the image from the camera (it should be just a screenshot).
To solve this:
ScreenshotDetectionDelegate.java
ScreenshotDetectionActivity.java
MainActivity.java
This code works, but has problems with some devices eg: Android 6.0 on Nexus 7 gives content://media/external/images/media as the uri in onChange, which can't resolve to the file path correctly.
Although the answer does not answer all the needs, but it can be a push base to obtain other ideas, I hope it will serve you. Cheers!