public void download(String url, String fileName) { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { Uri uri = Uri.parse(url); DownloadManager.Request r = new DownloadManager.Request(uri); r.setAllowedNetworkTypes(Request.NETWORK_WIFI); r.setAllowedOverRoaming(false); // set mime type MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeType = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)); r.setMimeType(mimeType); // set in notification r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); r.setVisibleInDownloadsUi(true); // sdcard if (TextUtils.isEmpty(fileName)) fileName = uri.getLastPathSegment(); r.setDestinationInExternalFilesDir(mContext, File.separator, fileName); r.setTitle(fileName); // start download mDownloadId = mDM.enqueue(r); } else if (mListener != null) { SystemClock.sleep(1000); mListener.onDownloadComplete(null); } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_DOWNLOAD_COMPLETE.equals(action)) { handleDownloadComplete(intent.getLongExtra(EXTRA_DOWNLOAD_ID, 0)); } else if (ACTION_NOTIFICATION_CLICKED.equals(action)) { mDM.remove(intent.getLongArrayExtra(EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)); if (mListener != null) { mListener.onDownloadComplete(null); } } }
private void handleDownloadComplete(long downloadId) { if (downloadId == mDownloadId) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadId); Cursor c = mDM.query(query); File file = null; if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(COLUMN_STATUS)); if (status == STATUS_SUCCESSFUL) { int index = c.getColumnIndex(COLUMN_LOCAL_FILENAME); file = new File(c.getString(index)); } if (mListener != null) { mListener.onDownloadComplete(file); } } } }