[英]Download file using Download Manager from AsyncTask
I'm working on an Android app that allows users to select a file from a list view and download it. 我正在开发一个Android应用,该应用允许用户从列表视图中选择一个文件并下载。 I have an AsyncTask
that fetches the files and for each file sets an onClickListener
which allows to download that file when the users clicks it. 我有一个AsyncTask
来提取文件,并为每个文件设置一个onClickListener
,当用户单击该文件时可以下载该文件。 I have all over the internet but I can't get a download manager to work from an AsynTask
. 我遍布互联网,但无法通过AsynTask
获得下载管理器。 Any help would be apreciated. 任何帮助将不胜感激。
Here is the simple example: 这是简单的示例:
btnDown.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String dir = Environment.DIRECTORY_MUSIC;
dir += "/klp";
File fileDir = new File(dir);
if (!fileDir.isDirectory()) {
fileDir.mkdir();
}
Toast.makeText(Detail.this, "Download song " + name, Toast.LENGTH_SHORT).show();
// Download File
DownloadManager.Request request =
new DownloadManager.Request(Uri.parse(url));
request.setDescription(nameFile);
request.setTitle(name);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(dir, nameFile);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.