我真的很想說聲謝謝你的所有評論。經過幾個小時的研究,我認爲使用BroadcastReceiver解決這個問題應該是最好的解決方案。以下,我想分享與我有同樣問題的人的答案。
我創建了一個靜態函數來處理下載:
public static long downloadVideo(String myHTTPUrl, Context context) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl));
request.setTitle("File download.");
request.setDescription("File is being download...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
final String nameOfFile = URLUtil.guessFileName(myHTTPUrl, null,
MimeTypeMap.getFileExtensionFromUrl(myHTTPUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
return manager.enqueue(request);
}
當我點擊按鈕下載,然後它會運行下面的代碼:
long downloadReference = DownloadHandler.downloadVideo(videoUrls[0], v.getContext());
DownloadReceiver downloadReceiver = new DownloadReceiver(0, videoUrls, downloadReference);
//set filter to only when download is complete and register broadcast receiver
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, filter);
這裏是最後一步,該廣播接收器:
public class DownloadReceiver extends BroadcastReceiver {
private int videoIndex;
private String[] videoUrls;
private long downloadReference;
public DownloadReceiver(int videoIndex, String[] videoUrls, long downloadReference) {
this.videoIndex = videoIndex;
this.videoUrls = videoUrls;
this.downloadReference = downloadReference;
}
@Override
public void onReceive(Context context, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if(downloadReference == referenceId){
++videoIndex;
if (videoIndex < videoUrls.length) {
downloadReference = DownloadHandler.downloadVideo(videoUrls[videoIndex], context);
DownloadReceiver downloadReceiver = new DownloadReceiver(videoIndex, videoUrls, downloadReference);
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.registerReceiver(downloadReceiver, intentFilter);
context.unregisterReceiver(this);
}
}
}
}
到目前爲止您嘗試過什麼? –
我使用BroadcastReceiver知道下載何時完成。然後,我開始訂單,但我認爲這不是一個好的解決方案 – LuongTruong
它以一種更簡單的方式做事。我似乎沒有任何最好的方法。 –