DownloadManager和Media

DownloadManager和Media

我正在尝试通过下载管理器下载一个图像,并将其显示在Gallery应用程序中,但我没有做任何工作。根据文档,我认为这段代码就足够了:

  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);
                          }
                     });
                 }
             }
         }
     }
 };

那也不管用。用“file name”标记打印的uri类似于“content://downloads/my_downloads/97”,而不是下载的实际文件的名称。在下载应用程序中,文件名与服务器上的文件名相同。用“媒体扫描程序”标记记录的uri为空。
我是不是遗漏了一些简单的东西?这件事我已经拔了几个小时头发了。

最佳答案

我想出来了。我必须添加一个下载位置。下面这一行修复了它。

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

关于android - Android DownloadManager和Media Scanner,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22736258/

10-09 00:31