[英]Updating ContentResolver to get updated file count
我正在使用棉花糖版本的Android中的外部存儲使用Storage Access Framework
刪除一些文件。 我需要顯示外部存儲中可用的各種文件的數量。 我正在為內部存儲獲得適當的計數,但是對於外部存儲,我沒有獲得視頻的更新文件計數。 每當我打開內置文件管理器然后返回到應用程序時,它都會正確更新文件計數,這意味着我需要調用某種方法來更新ContentResolver。
這是我獲取外部存儲中視頻數量的方法
private long[] findSize(StorageSource source, FileTypes type) {
Uri uri = MediaStore.Files.getContentUri(CONTENT_URI_COMMON);
String[] projection = { MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE };
String selection = getSelectionQuery(type);
String[] selectionArgs = {};
long total = 0;
int count = 0;
String sortOrder = null;
Cursor allExtMediaFiles = populateQueries(uri, projection, selection, selectionArgs, sortOrder);
synchronized (allExtMediaFiles) {
if (allExtMediaFiles != null) {
if (allExtMediaFiles.moveToFirst())
do {
if (isValidFamily(allExtMediaFiles.getString(0), source)) {
total = total + allExtMediaFiles.getLong(1);
count++;
}
} while (allExtMediaFiles.moveToNext());
allExtMediaFiles.close();
}
}
return new long[] { total, count };
}
private Cursor populateQueries(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(uri, projection, selection, selectionArgs, sortOrder);
cursor.setNotificationUri(cr,uri);
return cursor;
}
我試圖使用不同的方法來獲取正確的文件數,包括調用cursor.setNotificationUri(cr,uri);
, ContentResolver
上的notifyChange()
,也可以使用MediaScanner
。 這是刪除視頻文件后使用的代碼-
Uri uri = MediaStore.Files.getContentUri("external");
getActivity().getContentResolver().notifyChange(uri, null);
MediaScannerConnection.scanFile(getActivity(), new String[] {
path},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String scanPath, Uri scanUri)
{
Log.d(TAG,"Path "+scanPath+" uri"+scanUri.toString());
}
});
這里的path
是DocumentFile
的String Uri,它剛剛使用Storage Access Framework
刪除了。 我也嘗試在notifyChange()
方法中使用它。
那么,如何更新ContentResolver以返回更新后的文件計數?
刪除功能后嘗試此行
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
(以上解決方案自android 4.4起似乎不起作用)
對於DATA:
MediaStore.MediaColumns.DATA
你也可以嘗試使用這個
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(fileDeleted)));
請參閱此鏈接以獲取(一種)詳細的方法:
http://sandersdenardi.com/querying-and-removing-media-from-android-mediastore/
還請記住:
所有查詢和刪除(以及與此相關的插入和更新)都將阻塞,直到基礎事務完成為止。 您應該在單獨的線程上異步地對ContentResolver執行這些操作。 盡管在MediaStore上進行刪除根本不需要花費大量時間,但是如果在主線程上執行操作,則會阻塞UI。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.