ACTION_MEDIA_SCANNER_SCAN_FILE 总是不会将文件添加到 MediaStorage

ACTION_MEDIA_SCANNER_SCAN_FILE doesn't add file to MediaStorage always

我有以下行

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileOnDownload)));

其中 fileOnDownload 是像这样的文件的路径:

/storage/emulated/0/Downloads/song.mp3

但有时发送广播时,它不会重新加载 MediaStore(至少在 Android O 上)
可以查看完整代码 here
我是 Android MediaStore 的新手所以请不要太粗鲁:)

试试这个代码:

Intent intent = 
      new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);

如果以上代码不起作用,您可以尝试使用 MediaScannerConnection!

这里有一个很好的教程:

https://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/