2014-10-09 29 views
1

是否有一個簡單的機制來確定DownloadManager remove()何時完成,因爲它似乎是部分異步的。該函數幾乎立即返回下載表中它被刪除的條目的計數,但實際的文件系統看家似乎被推入某個後臺線程。Android DownloadManager remove() - 如何確定remove()操作何時完成?

問題是我寫的代碼,以查找並刪除文件X(並希望該文件系統對象)的任何現有的下載管理器進入,拉動新副本之前一點點。不幸的是,新副本在文件系統內務管理進入之前已經進入了目錄,對於以前的版本。因此,內務管理實際上最終會刪除新版本,並在DownloadManager表中留下孤立條目。

可以做一些方法來阻止,直到文件系統刪除的付諸行動。

調試代碼:

DownloadManager.Query query = new DownloadManager.Query().setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL); 
    downloads = getAllDownloadIds(manager.query(query)); 

    path = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); 

    //If a file name was passed remove any existing entry/version of the file 
    if (fileName != null && ! fileName.isEmpty()){ 
     if (downloads.containsKey(fileName)){ 
      ids = downloads.get(fileName); 
      for (Long id : ids) { 
       Uri path = manager.getUriForDownloadedFile(id); 
       File checkFile = new File(path.toString()); 
       Log.e(TAG, "Removing existing file: " + path.toString() + ":" + id); 
       int entriesRemoved = manager.remove(id); 
       Log.e(TAG, "Existing files removed: " + entriesRemoved);     
      } 
     } 
    } 


... 
Log.v(TAG, "Attempting to create a file in the 'Download' directory on the external storage::" + path.toString() +"/"+ fileName); 
file = new File(path, fileName); 
Log.v(TAG, "Does the file already exist::" + file.exists()); 

輸出示例:

… V/Export﹕ Removing existing file: file:///storage/sdcard/Download/appData.csv:101 
… V/Export﹕ Existing files removed: 1 
… V/Export﹕ Attempting to create a file in the 'Download' directory on the external storage::/storage/sdcard/Download/appData.csv 
… V/Export﹕ Does the file already exist::true 
+0

把您的目的地在一個臨時文件夾在外部存儲的包文件夾,並自行將其刪除。 – mmlooloo 2014-10-09 02:23:11

回答

1

我有同樣的問題 - 在一個快速網絡替換小文件時,替換文件有時會的一小部分內到達第二個在呼叫DownloadManager.remove(...)後在這種情況下,新到的文件將被刪除。

我使用的解決方案是,在我撥打DownloadManager.remove(...)之前,我設置了一個FileObserver來監視文件。然後我打電話給remove(...),但在啓動替換下載之前,請等待DELETE事件觸發。

這結束是多個類間分佈的代碼量顯著。還有其他一些複雜的因素 - 例如我爲了防止DownloadManager從不刪除文件而設置超時機制。 (我無法想象爲什麼它不會,但它不是我的組件)。

那麼,現在回答這個問題:「有沒有一種簡單的機制.....」:有機制,提供給你,但遺憾的是特別不容易的。

0

我我解決了這個計時問題的方法就是刪除DownloadManager.remove功能之前,該文件。無論如何,「下載」功能將刪除對下載的引用。

int idFromCursor = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_ID)); 
String localPathOfFile =cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); 
File fileToDelete= new File(localPathOfFile); 

if(fileToDelete.exists()){ 
    fileToDelete.delete(); 
} 
downloadManager.remove(idFromCursor); 

之後沒有時間問題了。