2015-12-22 129 views
0

我正在使用下載管理器來下載Android設備上的視頻。問題是我想下載多個視頻(一個接一個)。Android:逐個下載視頻

我研究了一整天,但有一些關於下載單個視頻的解決方案。

之後,我發現了同樣的問題在這裏,但沒有人回答: How to Download 45 videos one by one non stop with Download Manager?

如果你們知道如何做到這一點,請讓我知道。

預先感謝您!

+0

到目前爲止您嘗試過什麼? –

+0

我使用BroadcastReceiver知道下載何時完成。然後,我開始訂單,但我認爲這不是一個好的解決方案 – LuongTruong

+0

它以一種更簡單的方式做事。我似乎沒有任何最好的方法。 –

回答

0

我真的很想說聲謝謝你的所有評論。經過幾個小時的研究,我認爲使用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); 
     } 
    } 
} 

}