其他分享
首页 > 其他分享> > Android DownloadManager和Media Scanner

Android DownloadManager和Media Scanner

作者:互联网

我正在尝试通过DownloadManager下载图像以显示在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);
                          }
                     });
                 }
             }
         }
     }
 };

这也行不通.使用“filename”标签打印的URI类似于“content:// downloads / my_downloads / 97”,而不是下载的实际文件的名称.在下载应用程序中,文件名与服务器上的文件名相同.使用“Media Scanner”标记记录的Uri为空.

我错过了一些简单的东西吗?我一直把头发拉了几个小时.

解决方法:

我想到了.我不得不添加一个下载位置.以下行修复了它.

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

标签:android,android-download-manager,android-mediascanner
来源: https://codeday.me/bug/20190830/1771737.html