下面列出了android.app.DownloadManager#Request ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private long requestDownload(int x, int y, boolean hillshade) {
String ext = hillshade ? "mbtiles" : "mtiles";
String fileName = String.format(Locale.ENGLISH, "%d-%d.%s", x, y, ext);
Uri uri = new Uri.Builder()
.scheme("https")
.authority("trekarta.info")
.appendPath(hillshade ? "hillshades" : "maps")
.appendPath(String.valueOf(x))
.appendPath(fileName)
.build();
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(mContext.getString(hillshade ? R.string.hillshadeTitle : R.string.mapTitle, x, y));
request.setDescription(mContext.getString(R.string.app_name));
File root = new File(mMapsDatabase.getPath()).getParentFile();
File file = new File(root, fileName);
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
request.setDestinationInExternalFilesDir(mContext, root.getName(), fileName);
request.setVisibleInDownloadsUi(false);
return mDownloadManager.enqueue(request);
}
@OnClick(R.id.download_button)
public void downloadImage() {
String imageUrl = imageUrlList.get(imageViewPager.getCurrentItem());
String fileName = StringUtils.getImageNameFromUrl(imageUrl);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + "/scallop";
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imageUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(fileName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(path, fileName);
downloadManager.enqueue(request);
}
/**
* 下载最新APK
*/
private void downloadApk(String url) {
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadObserver = new DownloadChangeObserver();
registerContentObserver();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
/**设置用于下载时的网络状态*/
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
/**设置通知栏是否可见*/
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
/**设置漫游状态下是否可以下载*/
request.setAllowedOverRoaming(false);
/**如果我们希望下载的文件可以被系统的Downloads应用扫描到并管理,
我们需要调用Request对象的setVisibleInDownloadsUi方法,传递参数true.*/
request.setVisibleInDownloadsUi(true);
/**设置文件保存路径*/
request.setDestinationInExternalFilesDir(getApplicationContext(), "phoenix", "phoenix.apk");
/**将下载请求放入队列, return下载任务的ID*/
downloadId = downloadManager.enqueue(request);
registerBroadcast();
}
private long downloadFromUrl(String youtubeDlUrl, String downloadTitle, String fileName, boolean hide)
{
Uri uri = Uri.parse(youtubeDlUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(downloadTitle);
if (hide) {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setVisibleInDownloadsUi(false);
} else
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
return manager.enqueue(request);
}
/**
* 下载apk
*/
private long downloadApk(String url) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//创建目录, 外部存储--> Download文件夹
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;
File file = new File(Constant.PATH_APK);
if(file.exists())
file.delete();
//设置文件存放路径
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS , "WanAndroid.apk");
//设置Notification的标题
request.setTitle(mContext.getString(R.string.app_name));
//设置描述
request.setDescription(mContext.getString(R.string.downloading)) ;
// 在下载过程中通知栏会一直显示该下载的Notification,在下载完成后该Notification会继续显示,直到用户点击该Notification或者消除该Notification。
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED ) ;
//下载的文件可以被系统的Downloads应用扫描到并管理
request.setVisibleInDownloadsUi( true ) ;
//设置请求的Mime
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
request.setMimeType(mimeTypeMap.getMimeTypeFromExtension(url));
//下载网络需求 - 手机数据流量、wifi
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI ) ;
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
return downloadManager.enqueue(request);
}
/**
* Starts a map download.
*
* This will also start the progress checker.
*
* @param rfile The remote file to download
* @param mapFile The local file to which the map will be saved
* @param view The {@link View} displaying the map file
*/
private void startDownload(RemoteFile rfile, File mapFile, View view) {
Uri uri = rfile.getUri();
Uri destUri = Uri.fromFile(mapFile);
try {
DownloadManager.Request request = new DownloadManager.Request(uri);
//request.setTitle(rfile.name);
//request.setDescription("SatStat map download");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//request.setDestinationInExternalFilesDir(getActivity(), dirType, subPath)
request.setDestinationUri(destUri);
Log.d(TAG, String.format("Ready to download %s to %s (local name %s)", uri.toString(), destUri.toString(), mapFile.getName()));
Long reference = downloadManager.enqueue(request);
DownloadInfo info = new DownloadInfo(rfile, uri, mapFile, reference);
downloadsByReference.put(reference, info);
downloadsByUri.put(rfile.getUri(), info);
downloadsByFile.put(mapFile, info);
ProgressBar downloadFileProgress = (ProgressBar) view.findViewById(R.id.downloadFileProgress);
downloadFileProgress.setVisibility(View.VISIBLE);
downloadFileProgress.setMax((int) (rfile.size / 1024));
downloadFileProgress.setProgress(0);
startProgressChecker();
} catch (SecurityException e) {
Log.w(TAG, String.format("Permission not granted to download %s to %s", uri.toString(), destUri.toString()));
}
}
private DownloadManager.Request createRequest(@NonNull String url,
@NonNull String filename,
@Nullable String destinationPath,
@NonNull String mimeType,
boolean inPublicDir,
boolean showCompletedNotification) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription(filename);
request.setMimeType(mimeType);
if (destinationPath == null) {
destinationPath = Environment.DIRECTORY_DOWNLOADS;
}
File destinationFolder = inPublicDir
? Environment.getExternalStoragePublicDirectory(destinationPath)
: new File(context.getFilesDir(), destinationPath);
createFolderIfNeeded(destinationFolder);
removeDuplicateFileIfExist(destinationFolder, filename);
if (inPublicDir) {
request.setDestinationInExternalPublicDir(destinationPath, filename);
} else {
request.setDestinationInExternalFilesDir(context, destinationPath, filename);
}
request.setNotificationVisibility(showCompletedNotification
? DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
: DownloadManager.Request.VISIBILITY_VISIBLE);
return request;
}
public void downloadFile(View v){
if(gInstance.fileName.equals("")){
MainActivity.showMessage("Missing file!", this);
return;
}
String url=MainActivity.WEBSITE +"/"+ gInstance.media;
try{
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(gInstance.fileName);
request.setDescription(MainActivity.WEBSITE);
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); only download thro wifi.
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(GraphicActivity.this, gInstance.fileName+" Downloaded!", Toast.LENGTH_SHORT).show();
}
};
manager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}catch(Exception e){
MainActivity.showMessage(e.getMessage(), this);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = getContext2();
if (null != context && null != mTorrentList && position < mTorrentList.length) {
String url = mTorrentList[position].first;
String name = mTorrentList[position].second;
// Use system download service
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(url));
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
FileUtils.sanitizeFilename(name + ".torrent"));
r.allowScanningByMediaScanner();
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
if (dm != null) {
try {
dm.enqueue(r);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
}
}
}
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
private void downloadNormal(String fileName, YTConfig config) {
Uri uri = Uri.parse(config.getUrl());
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(config.getTitle()+" - "+config.getChannelTitle());
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
/**
* 开始下载
* @param url url
* @param artist artist
* @param title title
* @param coverPath path
*/
void downloadMusic(String url, String artist, String title, String coverPath) {
try {
String fileName = FileMusicUtils.getMp3FileName(artist, title);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(FileMusicUtils.getFileName(artist, title));
request.setDescription("正在下载…");
request.setDestinationInExternalPublicDir(FileMusicUtils.getRelativeMusicDir(), fileName);
request.setMimeType(MimeTypeMap.getFileExtensionFromUrl(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
// 不允许漫游
request.setAllowedOverRoaming(false);
DownloadManager downloadManager = (DownloadManager) Utils.getApp().getSystemService(Context.DOWNLOAD_SERVICE);
long id = 0;
if (downloadManager != null) {
id = downloadManager.enqueue(request);
}
String musicAbsPath = FileMusicUtils.getMusicDir().concat(fileName);
DownloadMusicInfo downloadMusicInfo = new DownloadMusicInfo(title, musicAbsPath, coverPath);
BaseAppHelper.get().getDownloadList().put(id, downloadMusicInfo);
} catch (Throwable th) {
th.printStackTrace();
ToastUtils.showShort("下载失败");
} finally {
}
}
/**
* date: 7/12/17
* author: chenli
* description: 利用系统的下载服务
*/
private void downLoadFile(String url, String contentDisposition, String mimetype) {
//创建下载任务,downloadUrl就是下载链接
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//指定下载路径和下载文件名
request.setDestinationInExternalPublicDir("/download/", URLUtil.guessFileName(url, contentDisposition, mimetype));
//获取下载管理器
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
//将下载任务加入下载队列,否则不会进行下载
if (downloadManager != null) downloadManager.enqueue(request);
ToastUtils.showToast(BaseApplication.getContext(),
"下载完成:" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath() + File.separator + URLUtil.guessFileName(url, contentDisposition, mimetype));
}
private void downloading() {
if(isStoragePermissionGranted()){
DownloadManager mgr = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request req=new DownloadManager.Request(uri);
req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(title)
.setDescription("downloading...")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,title);
mgr.enqueue(req);
}
}
public void downloadFile(View v){
if(gInstance.fileName.equals("")){
MainActivity.showMessage("Missing file!", this);
return;
}
String url=MainActivity.WEBSITE +"/"+ gInstance.media;
try{
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(gInstance.fileName);
request.setDescription(MainActivity.WEBSITE);
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); only download thro wifi.
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(GraphicActivity.this, gInstance.fileName+" Downloaded!", Toast.LENGTH_SHORT).show();
}
};
manager.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}catch(Exception e){
MainActivity.showMessage(e.getMessage(), this);
}
}
private void downLoadApk(String url) {
if (mEnqueue == 0) {
mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(getString(R.string.app_name));
request.setDescription(getString(R.string.text_downloading));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, APK_NAME);
request.setVisibleInDownloadsUi(true);
mEnqueue = mDownloadManager.enqueue(request);
}
}
/**
* 执行下载任务
*
* @param apkUri apk的下载地址
* @param apkName 要保存的apk名字
* @return 下载任务的ID
*/
public long downloadAPK(String apkUri, String apkName) {
Assert.notNull(apkUri);
Assert.notNull(apkName);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUri));
request.setMimeType("application/vnd.android.package-archive");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
long id = mDownloadManager.enqueue(request);
sIds.add(id);
return id;
}
@Override
public void onLrc(int position, String url) {
if(url == null) return;
String musicName = mResultData.get(position).getMusicName();
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(Constants.MUSIC_URL + url));
request.setVisibleInDownloadsUi(false);
request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
// request.setShowRunningNotification(false);
request.setDestinationUri(Uri.fromFile(new File(MusicUtils
.getLrcDir() + musicName + ".lrc")));
mDownloadManager.enqueue(request);
}
public static void StartFlashRecovery(String downloadLink, String downloadDirectory, String downloadedFileFinalName, String recoveryPartition) {
Uri mDownloadLink = Uri.parse(downloadLink);
File mDownloadDirectory = new File(downloadDirectory);
DownloadManager.Request mRequest = new DownloadManager.Request(mDownloadLink);
mRequest.setDestinationInExternalPublicDir(mDownloadDirectory.getPath(), downloadedFileFinalName);
mRequest.setTitle(ACTIVITY.getString(R.string.app_name));
mRequest.setDescription(downloadedFileFinalName);
new FlashRecovery(
mRequest,
mDownloadDirectory,
downloadedFileFinalName,
recoveryPartition, false).execute();
}
public static void StartDownloadROM(String downloadLink, String downloadDirectory, String downloadedFileFinalName) {
FILE_NAME = downloadedFileFinalName;
Uri mDownloadLink = Uri.parse(downloadLink);
File mDownloadDirectory = new File(downloadDirectory);
DownloadManager.Request mRequest = new DownloadManager.Request(mDownloadLink);
mRequest.setDestinationInExternalPublicDir(mDownloadDirectory.getPath(), downloadedFileFinalName);
mRequest.setTitle(ACTIVITY.getString(R.string.app_name));
mRequest.setDescription(downloadedFileFinalName);
new Download(
mRequest,
mDownloadDirectory,
FILE_NAME, true).execute();
}
FlashRecovery(DownloadManager.Request request, File downloadDirectory, String downloadedFileFinalName, String recoveryPartition, Boolean hasAddOns) {
this.mRequest = request;
this.mDownloadDirectory = downloadDirectory;
this.mDownloadedFileFinalName = downloadedFileFinalName;
this.mRecoveryPartition = recoveryPartition;
this.mHasAddOns = hasAddOns;
}