我正在尝试使用AsyncTask中的DownloadManager下载文件
private class DownloadTask extends AsyncTask<String, Void, Boolean>
{
private Context mContext;
public DownloadTask(Context context)
{
mContext = context;
}
@Override
protected Boolean doInBackground(String... strings) {
String fileName = strings[2]+"_"+strings[3]+ strings[4];
String destination = mDestination + fileName;
final Uri uri = Uri.parse("file://" + destination);
mDownloading = true;
//If the file is already downloading just return.
File file = new File(destination);
if (file.exists()) {
return true;
}
//set downloadmanager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(strings[0]));
request.setDescription(mContext.getString(R.string.downloading)+ " "+strings[1]);
request.setTitle(mContext.getString(R.string.downloading_title));
//set destination
request.setDestinationUri(uri);
// get download service and enqueue file
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
//set BroadcastReceiver to enable next download
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
unregisterReceiver(this);
mDownloading = false;
}
};
//register receiver for when file download is compete
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
return true;
}
}`
当我传递文件的URL时,代码工作正常。问题是,我们想要对PHP上的WEB进行GET调用。此WEB方法创建或选择文件,并使用标题("Location: ".$database->single()['Url']);
但是当我们从DownloadManager进行调用时,它只是立即调用registerReceiver。
有谁知道为什么会这样?
如果我们使用HttpURLConnection
它工作正常,但我们想在DownloadManager中委派下载的所有辛苦工作。
感谢您的评论。
答案 0 :(得分:0)
3xx:DownloadManger不支持重定向。 Source code第510行
它将下载重定向响应并以正确的方式完成。
因此,您应该自己获得响应头[Location],并将其传递给任务。
顺便说一下,您不需要将下载任务放在AsyncTask中。