Android下载带回调的文件列表

时间:2015-03-31 17:09:45

标签: android android-asynctask

我有一个活动,我需要从中下载并保存文件列表。文件和名称存储在Map <String,String>中。下载了我需要在我的Activity中调用函数的所有文件。

我已经有AsyncTask类下载和保存文件以及回调到Activity的接口。 我如何将Map<String,String>传递给Asynctask,或者可能还有其他解决方案?

感谢。

2 个答案:

答案 0 :(得分:1)

这不适合AsyncTask。您应该考虑实现自定义服务,可能是IntentService。

http://www.vogella.com/tutorials/AndroidServices/article.html

有一个非常好的教程

答案 1 :(得分:0)

我建议使用Android DownloadManager和ID列表

DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("http://www.example.com/myfile.mp3");

DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("My File");
request.setDescription("Downloading");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(false);
request.setDestinationUri(Uri.parse("file://" + folderName + "/myfile.mp3"));

mList_refid.add(downloadmanager.enqueue(request));

要设置回调,请使用registerReceiver

mList_refid = new ArrayList<>();
mDownloadReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            if (mList_refid != null && mList_refid.contains(downloadId)) {
                mList_refid.remove(downloadId); // File is downloaded, remove it from ID list.
            }
        } else
            Log.e(LOG, "BroadcastReceiver on receive action not handled : " + action);
    }
};
registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));