2014-03-29 71 views
2

我想通過DownloadManager下載圖片以顯示在圖庫應用程序中,但沒有任何工作。根據該文件,我想這個代碼就足夠了:Android DownloadManager和媒體掃描儀

public void downloadImage(String url) { 
     Uri Download_Uri = Uri.parse(url); 
     DownloadManager.Request request = new DownloadManager.Request(Download_Uri); 
     request.allowScanningByMediaScanner(); 
     download_id = downloadManager.enqueue(request); 
    } 

但是當文件下載,它不會在Gallery應用程序顯示出來。所以我嘗試下載接收器手動添加它,如下所示:

BroadcastReceiver receiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
      long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
      Query query = new Query(); 
      query.setFilterById(downloadId); 
      Cursor c = downloadManager.query(query); 
      if (c.moveToFirst()) { 
       int columnIndex = c 
         .getColumnIndex(DownloadManager.COLUMN_STATUS); 
       if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { 
        String uriString = downloadManager.getUriForDownloadedFile(download_id).toString(); 
          //c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); 
        Log.i("filname", uriString); 
        MediaScannerConnection.scanFile(ArticleActivity.this, 
           new String[] { uriString }, null, 
           new MediaScannerConnection.OnScanCompletedListener() { 
          public void onScanCompleted(String path, Uri uri) { 
           Log.i("Media Scanner", "Scanned " + path + ":"); 
           Log.i("Media Scanner", "-> uri=" + uri); 
          } 
        }); 
       } 
      } 
     } 
    } 
}; 

這也行不通。用「filename」標籤打印的URI與「content:// downloads/my_downloads/97」類似,而不是下載的實際文件的名稱。在下載應用程序中,文件名與服務器上的文件名相同。 Uri使用「媒體掃描儀」標籤記錄爲空。

我在這裏錯過了一些簡單的東西嗎?我一直在這裏拉我的頭髮幾個小時。

回答

3

我想通了。我不得不添加一個下載位置。以下行修復了它。

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, Download_Uri.getLastPathSegment()); 
2

接受的答案是適合我的,直到我在Android 6.0中測試它。我不確定這是否是無證的更改,但downloadManager.getUriForDownloadedFile(download_id)總是返回一個類型爲content://downloads/my_downloads/97的URI,無論我是否在下載請求中設置文件目標。

如何我固定它是通過使用光標從下載管理器:

Query query = new Query(); 
query.setFilterById(downloadId); 
Cursor cursor = downloadManager.query(query); 
if (cursor.moveToFirst()) { 
    String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME)); 
}