Android文件管理器與media數據庫的同步問題
https://www.eoeandroid.com/thread-112212-1-1.html
Bug Description:
當在文件管理器中修改多媒體文件(包含音樂、視頻、圖片)後,音樂播放器、視頻播放器、gallery app中顯示被修改的文件,且打開失敗。Android Recorder(錄音機)也出現相同問題。
Root Cause:
Android係統自帶了一個media數據庫,每次開機完成後,係統會自動掃描SD卡和係統並將音樂、視頻、圖片三類多媒體文件存放到media數據庫中對應的表中。當打開對應APP時,APP會從media數據庫中查詢對應的文件,並顯示給用戶。此問題原因在於,文件文件管理器修改的文件沒有同步到media數據庫中,導致APP不能得到最新的文件數據。
Solution:
文件管理器每次修改多媒體文件時,都要將其修改同步到數據庫中。
同步方法:
1. 添加文件
當添加一個文件後,可發送ACTION_MEDIA_SCANNER_SCAN_FIL的廣播,MediaProvider捕獲到這個廣播後,就會掃描添加的文件並將其添加到數據庫中。
參考代碼:
private void notyfyMediaAdd(File file){
if(file.isDirectory()) {
File[] children = file.listFiles();
for (File child : children) {
notyfyMediaAdd(child);
}
return;
}
String type = "";
type = FileUtilMsg.getFileMimeType(file);
if(type.startsWith("audio/")
|| type.startsWith("video/")
|| type.startsWith("image/")
|| type.equals("application/ogg")
|| type.equals("application/x-ogg")
|| type.equals("application/itunes")) {
String uriStr = file.getAbsolutePath().replaceFirst(".*/?sdcard", "file:///mnt/sdcard");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(uriStr)));
}
}
2. 刪除文件
直接調用MediaProvider的delete函數進行刪除。
參考代碼:
private void notifyMediaRemove(File file){
String type = "", where = "";
type = FileUtilMsg.getFileMimeType(file);
String path = file.getAbsolutePath().replaceFirst(".*/?sdcard", "/mnt/sdcard");
if(type.equals("")) {
where = MediaStore.Audio.Media.DATA + " LIKE '" + path + "%'";
getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null);
where = MediaStore.Video.Media.DATA + " LIKE '" + path + "%'";
getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, where, null);
where = MediaStore.Images.Media.DATA + " LIKE '" + path + "%'";
getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, where, null);
return;
}
if(type.startsWith("audio/")
|| type.equals("application/ogg")
|| type.equals("application/x-ogg")
|| type.equals("application/itunes")) {
where = MediaStore.Audio.Media.DATA + "='" + path + "'";
getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null);
} else if(type.startsWith("video/")) {
where = MediaStore.Video.Media.DATA + "='" + path + "'";
getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, where, null);
} else if(type.startsWith("image/")) {
where = MediaStore.Images.Media.DATA + "='" + path + "'";
getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, where, null);
}
}
3. 更新文件:移動、重命名
可以先刪除原文件,再添加新文件來進行更新。
參考代碼:
調用上述刪除和添加的函數。
也可以直接調用MediaProvider的update函數進行更新;
最後更新:2017-04-03 18:52:11