自动删除最新的屏幕截图

时间:2016-06-23 21:47:03

标签: android

我正在尝试实现一种方法,该方法将检测屏幕截图何时创建并立即将其删除。我正在使用FileObserver观察屏幕截图目录,并在所述目录中创建新文件时进行标记。我不知道语法是完全正确的,所以任何帮助将不胜感激。谢谢!

private void deleteMostRecentScreenshot() {
    /**
     * Set the path for the screenshot directory.
     */

    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "Screenshots";
    OLog.d(TAG, path);
    /**
     * Array of the files in our screenshot directory, sorted so that the oldest pictures are first.
     */

    final File[] screenshots = new File(path).listFiles();
    Arrays.sort(screenshots, new Comparator<File>() {
        @Override
        public int compare(File f1, File f2) {
            return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
        }
    });
    /**
     * Watch for when a new file is created in our directory, ignoring "probes" created when the camera
     * is launched. If a new file is created, delete the last file in the array, which should be
     * the newest picture.
     */
    FileObserver fileObserver = new FileObserver(path) {
        @Override
        public void onEvent(int event, String path) {

            OLog.d(TAG, event + "" + path);
            if (event == FileObserver.CREATE && !path.equals(".probe")) {
                OLog.d(TAG, "File Created ["
                        + Environment.getExternalStorageState()
                        + "Screenshots"
                        + path
                        + "]");
                screenshots[screenshots.length - 1].delete();
            }
        }
    };
    fileObserver.startWatching();

1 个答案:

答案 0 :(得分:0)

  

我问过其他一些与我合作的程序员,如果他们看到任何不合适的东西,看了很多其他的SO文章,但仍不确定为什么它没有按预期工作。

目前还不清楚你到底想要什么。以下是我看到的两个奇怪的事情:

  1. 您的FileObserver会随机停止观察文件,因为只要deleteMostRecentScreenshot()返回就有资格进行垃圾回收。并且,正如the documentation指出的那样,“如果FileObserver被垃圾收集,它将停止发送事件。为了确保您继续接收事件,您必须保持对来自其他一些活动对象的FileObserver实例的引用。”

  2. 您的声明“数组中的最后一个文件......应该是最新的图片”是不正确的。充其量,它是您调用listFiles()时最近修改过的文件。调用listFiles()后发生的更改不会影响您的screenshots数组。由于您为FileObserver指定了文件的路径,因此您可以考虑使用该路径。