Skip to content

Commit 3030db5

Browse files
Implement automatic deletion of old screenshots
This change introduces a limit to the number of screenshots stored by the ScreenCaptureService. When a new screenshot is taken, I now check the number of existing screenshots in the app's dedicated screenshot directory (`Android/data/com.google.ai.sample/files/Pictures/Screenshots/`). If saving a new screenshot would cause the total to exceed 100, the oldest screenshot(s) are deleted to maintain a maximum of 100. Screenshots are identified by the naming pattern "screenshot_yyyyMMdd_HHmmss.png", allowing for reliable sorting to find the oldest ones. Logging has been added to record the deletion of old screenshots or any failures in the deletion process. Manual testing is required to confirm this functionality by generating more than 100 screenshots and observing the file system and logs.
1 parent becb985 commit 3030db5

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

app/src/main/kotlin/com/google/ai/sample/ScreenCaptureService.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,33 @@ private fun takeScreenshot() {
332332
picturesDir.mkdirs()
333333
}
334334

335+
// List existing screenshot files
336+
val screenshotFiles = picturesDir.listFiles { _, name ->
337+
name.startsWith("screenshot_") && name.endsWith(".png")
338+
}?.toMutableList() ?: mutableListOf()
339+
340+
// Sort files by name (timestamp) to find the oldest
341+
screenshotFiles.sortBy { it.name }
342+
343+
// If count is 100 or more, delete oldest ones until count is 99
344+
// This makes space for the new screenshot, keeping the total at a max of 100
345+
val maxScreenshots = 100
346+
var screenshotsToDelete = screenshotFiles.size - (maxScreenshots -1) // Number of files to delete to make space for the new one
347+
348+
if (screenshotsToDelete > 0) {
349+
Log.i(TAG, "Max screenshots reached. Current count: ${screenshotFiles.size}. Attempting to delete $screenshotsToDelete oldest screenshot(s).")
350+
for (i in 0 until screenshotsToDelete) {
351+
if (i < screenshotFiles.size) {
352+
val oldestFile = screenshotFiles[i]
353+
if (oldestFile.delete()) {
354+
Log.i(TAG, "Deleted oldest screenshot: ${oldestFile.absolutePath}")
355+
} else {
356+
Log.e(TAG, "Failed to delete oldest screenshot: ${oldestFile.absolutePath}")
357+
}
358+
}
359+
}
360+
}
361+
335362
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
336363
val file = File(picturesDir, "screenshot_$timestamp.png")
337364

0 commit comments

Comments
 (0)