I'm trying to get an image downloaded via DownloadManager to show up in the Gallery app, but nothing I do works. According to the documentation, I thought this code would be sufficient:
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);
}
But when the file downloads, it does not show up in the Gallery app. So I tried a download receiver to add it manually, like so:
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);
}
});
}
}
}
}
};
That doesn't work either. The URI printed with the "filename" tag is something like 'content://downloads/my_downloads/97' instead of the name of the actual file that was downloaded. In the downloads app, the filename is the same as it was on the server. The Uri logged with the "Media Scanner" tag is null.
Am I missing something simple here? I've been pulling my hair out for a few hours on this.
I figured it out. I had to add a download location. The following line fixes it.
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, Download_Uri.getLastPathSegment());