我正在开发一款Android应用,允许用户从列表视图中选择文件并下载。我有一个AsyncTask
来获取文件,每个文件设置一个onClickListener
,允许在用户点击它时下载该文件。我有互联网,但我无法通过AsynTask
让下载管理员工作。任何帮助都会被贬低。
答案 0 :(得分:1)
以下是一个简单的例子:
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);
}
});