android - 如何正确通知 MediaScanner 有关文件夹的信息,即使是在 Nexus/Kitkat 设备上?

标签 android directory android-4.4-kitkat android-mediascanner

背景

我正在制作一个应用程序,它可以将一些图像从 Internet 下载到定义为的特定文件夹中:

final String pathToPutFiles = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + File.separator + DOWNLOAD_FOLDER_NAME;

我希望制作图库和任何显示媒体的应用程序,以便收到这些图像的通知并能够显示它们。

遗憾的是,我在 Nexus 4 上遇到问题,它有 Kitkat 版本(确切地说是 4.4.2)。有时有效,有时无效。

问题

关于这个问题有很多帖子,我已经尝试了很多,但没有一个使用简单的文件夹路径有效:

  • 使用 Intent 的 Intent 。 ACTION_MEDIA_SCANNER_SCAN_FILE ,如图here .这在任何设备上都不起作用
  • 创建 MediaScannerConnectionClient 的实例并在连接完成后调用扫描,如图所示 herehere .不确定这有什么问题,因为它确实连接成功。
  • 调用scanFile ,如图here ,有和没有听众。这在 Galaxy S3 上运行良好,但在 Nexus 4 上运行良好。这是我选择执行的操作,但我注意到它无法使用单个文件夹路径。相反,它需要一组文件来通知。

我尝试过的

这就是我所做的(同样,它在装有 Android 4.3 的 Galaxy S3 上工作正常,但有时在装有 Android 4.4.2 的 Nexus 4 上不起作用):

protected void notifyMediaScannerOfNewImageFiles(final String folderPathToScan) {
        final ArrayList<String> newFilesToScan = new ArrayList<String>();
        preparePaths(folderPathToScan, newFilesToScan, true);
        final String[] newFilesToScanArr = newFilesToScan.toArray(new String[newFilesToScan.size()]);
        MediaScannerConnection.scanFile(getApplicationContext(), newFilesToScanArr, null, null);
}

public static void preparePathsForMediaScanning(final String folderPathToScan, final Collection<String> pathsToFill,
        final boolean recursive) {
    if (TextUtils.isEmpty(folderPathToScan))
        return;
    final File folderToScan = new File(folderPathToScan);
    if (!folderToScan.exists())
        return;
    pathsToFill.add(folderPathToScan);
    if (!folderToScan.isDirectory())
        return;
    final File[] childrenFiles = folderToScan.listFiles();
    if (childrenFiles == null || childrenFiles.length == 0)
        return;
    for (final File childFile : childrenFiles) {
        if (childFile.exists()) {
            final String childFilePath = childFile.getAbsolutePath();
            pathsToFill.add(childFilePath);
            if (recursive && childFile.isDirectory())
                preparePathsForMediaScanning(childFilePath, pathsToFill, true);
        }
    }
}

问题

我应该如何通知要扫描整个文件夹?

为什么这种方法只在 Kitkat 上有时有效?它只是 Nexus 设备,还是其他设备?

应该使用什么来支持所有设备和 Android 版本?

最佳答案

到目前为止,我已经为这个问题苦苦思索了很长时间。如发布于 this SO anwser , 它似乎是 KitKat 上发生的错误。

issue Android 团队在内部和外部进行跟踪。

与此同时,这是我发现的:https://stackoverflow.com/a/23078323/1367571

关于android - 如何正确通知 MediaScanner 有关文件夹的信息,即使是在 Nexus/Kitkat 设备上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216646/

相关文章:

android - 从 Firebase 数据库获取值(value)

android - 如何在新列表适配器上将搜索方法添加到可过滤的列表中?

android - 获取ImageView顶部和底部的Y坐标

c++ - 如何使用 ntquerydirectoryfile 函数 Hook 隐藏文件夹

c - 从 Excel 文件自动创建文件夹

java - 无法在 Android KitKat 上将 txt 文件写入 SD 卡

android - Android 平板电脑上的插页式 dfp 广告未全屏显示

c++ - _chdir() 不改变目录 C++

android - 有什么方法可以通过tinymix命令捕获音频吗?

android - 如何在 RTL 布局中直接在图像上使用 "autoMirrored"属性