Android 当媒体变更后,通知其他应用重新扫描

时间:2023-03-09 19:49:13
Android 当媒体变更后,通知其他应用重新扫描

在媒体文件改变后 发出 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE广播,告知其他应用,媒体文件发生改变。

具体代码片段:

 File oldFile = new File(oldPath);
File newFile = new File(newPath);
if (oldFile.exists() && !newFile.exists()) {
if (oldFile.renameTo(newFile)) { Uri fileUri = Uri.fromFile(newFile);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(fileUri);
sendBroadcast(intent);
}
}

经过测试上面的代码在三星,联想的手机上不好用

经过试验 将面代码的 6- 10 行换成下面的代码就好用了

sendBroadcast(newIntent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory())));