2

我正在开发一个允许用户从列表视图中选择文件并下载的 Android 应用程序。我有一个AsyncTask可以获取文件并为每个文件设置一个onClickListener允许在用户单击它时下载该文件的文件。我在互联网上到处都是,但我无法让下载管理器从AsynTask. 任何帮助将不胜感激。

4

1 回答 1

2

这是一个简单的例子:

        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);   


        }
    });
于 2013-06-01T10:53:45.657 回答