2013-02-10 57 views
13

我在我的活動中使用了下載管理器類來執行下載;它工作正常,我的下一個任務是在我的活動中顯示相同的進度百分比。我不知道該怎麼做。在活動中顯示下載管理器進度

到目前爲止我的代碼

public class DownloadSampleBook extends Activity{ 

private long enqueue; 
private DownloadManager dm; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sample_download); 

    BroadcastReceiver receiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
       long downloadId = intent.getLongExtra(
         DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
       Query query = new Query(); 
       query.setFilterById(enqueue); 
       Cursor c = dm.query(query); 
       if (c.moveToFirst()) { 
        int columnIndex = c 
          .getColumnIndex(DownloadManager.COLUMN_STATUS); 
        if (DownloadManager.STATUS_SUCCESSFUL == c 
          .getInt(columnIndex)) { 

         view.setImageURI(Uri.parse(uriString)); 
        } 
       } 
      } 
     } 
    }; 

    registerReceiver(receiver, new IntentFilter(
      DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
} 

public void onClick(View view) { 
    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
    Request request = new Request(
      Uri.parse("http://abc.com/a.png")); 
    enqueue = dm.enqueue(request); 

} 

public void showDownload(View view) { 
    Intent i = new Intent(); 
    i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS); 
    startActivity(i); 
} 
} 

是否有給予的進展下載百分比的任何方法?

+0

想知道。沒有明確的解決方案 – 2013-05-17 14:03:47

回答

17

您可以使用query方法查詢到目前爲止已下載的字節數以及需要下載的總字節數,其方式與查詢示例代碼中的狀態非常相似。一旦你有了這些值,計算進度的百分比就相當容易了。

收到新數據時,您似乎沒有任何方式通知您,因此您需要定期輪詢下載管理器以確定您下載的當前狀態想要監視。

Query query = new Query(); 
query.setfilterById(downloadId); 

Cursor c = dm.query(query); 
if (c.moveToFirst()) { 
    int sizeIndex = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES); 
    int downloadedIndex = c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR); 
    long size = c.getInt(sizeIndex); 
    long downloaded = c.getInt(downloadedIndex); 
    double progress = 0.0; 
    if (size != -1) progress = downloaded*100.0/size; 
    // At this point you have the progress as a percentage. 
} 

請注意,總大小最初將爲-1,並且只會在下載開始後填充。所以在上面的示例代碼中,我檢查了-1,並且如果大小尚未設置,則將進度設置爲0。

但是,在某些情況下,您可能會發現從未返回總大小(例如,在HTTP分塊傳輸中將不存在可從中確定大小的Content-Length標頭)。如果你需要支持這種服務器,你可能應該向用戶提供一些指示,說明下載正在進行,而不僅僅是一個卡在零的進度條。

+0

不應該檢查零值的大小嗎?像下載的* 100.0 /(尺寸== 0?1:尺寸) – Fabiano 2015-02-28 00:55:30

18

如果你正在尋找一個體面的方式來確定何時查詢DownloadManager的最新進展,考慮爲URI content://downloads/my_downloads

實例註冊ContentObserver

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
manager.enqueue(myRequest); 

Uri myDownloads = Uri.parse("content://downloads/my_downloads"); 
getContentResolver().registerContentObserver(myDownloads, true, new DownloadObserver()); 

... 

public static class DownloadObserver extends ContentObserver { 
    @Override 
    public void onChange(boolean selfChange, Uri uri) { 
     Log.d("DownloadObserver", "Download " + uri + " updated"); 
    } 

這將產生以下輸出接收長時間運行的下載的每個塊

D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated 
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated 
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated 
D/DownloadObserver(15584): Download content://downloads/my_downloads/437 updated 

其中'437'是您下載的ID。

請注意,它遵循類似android.provider.Downloads中定義的內容URI,該內容URI似乎隱藏在框架中,可能無法在所有設備上一致地運行。 (https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/provider/Downloads.java#89

0

我有一個要求跟蹤下載多個文件。很多的思考和實驗後,我想出了下面的代碼:

private void startDownloadThread(final List<DownloadFile> list) { 

     // Initializing the broadcast receiver ... 
     mBroadCastReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       mFinishedFilesFromNotif.add(intent.getExtras() 
         .getLong(DownloadManager.EXTRA_DOWNLOAD_ID)); 
      } 
     }; 

     IntentFilter intentFilter = new IntentFilter(
       "android.intent.action.DOWNLOAD_COMPLETE"); 
     DownloadProgressUIFragment.this.getActivity().registerReceiver(mBroadCastReceiver, 
       intentFilter); 

     // initializing the download manager instance .... 
     mDownloadManager = (DownloadManager) getActivity() 
       .getSystemService(Context.DOWNLOAD_SERVICE); 

     // adding files to the download manager list ... 
     for(DownloadFile f: list) { 
      mDownloadIds.add(FileUtils.addFileForDownloadInBkg(getApplicationContext(), 
        f.getUrl(), 
        f.getPath())); 
     } 

     // starting the thread to track the progress of the download .. 
     mProgressThread = new Thread(new Runnable() { 
      @Override 
      public void run() { 

       // Preparing the query for the download manager ... 
       DownloadManager.Query q = new DownloadManager.Query(); 
       long[] ids = new long[mDownloadIds.size()]; 
       final List<Long> idsArrList= new ArrayList<>(); 
       int i = 0; 
       for (Long id: mDownloadIds) { 
        ids[i++] = id; 
        idsArrList.add(id); 
       } 
       q.setFilterById(ids); 

       // getting the total size of the data ... 
       Cursor c; 

       while(true) { 

        // check if the downloads are already completed ... 
        // Here I have created a set of download ids from download manager to keep 
        // track of all the files that are dowloaded, which I populate by creating 
        // 
        if(mFinishedFilesFromNotif.containsAll(idsArrList)) { 
         isDownloadSuccess = true; 

         // TODO - Take appropriate action. Download is finished successfully 
         return; 
        } 

        // start iterating and noting progress .. 
        c = mDownloadManager.query(q); 
        if(c != null) { 
         int filesDownloaded = 0; 
         float fileFracs = 0f; // this stores the fraction of all the files in 
         // download 
         final int columnTotalSize = c.getColumnIndex 
           (DownloadManager.COLUMN_TOTAL_SIZE_BYTES); 
         final int columnStatus = c.getColumnIndex(DownloadManager.COLUMN_STATUS); 
         //final int columnId = c.getColumnIndex(DownloadManager.COLUMN_ID); 
         final int columnDwnldSoFar = 
           c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR); 

         while (c.moveToNext()) { 
          // checking the progress .. 
          if(c.getInt(columnStatus) == DownloadManager.STATUS_SUCCESSFUL) { 
           filesDownloaded++; 
          } 
          // If the file is partially downloaded, take its fraction .. 
          else if(c.getInt(columnTotalSize) > 0) { 
           fileFracs += ((c.getInt(columnDwnldSoFar) * 1.0f)/
             c.getInt(columnTotalSize)); 
          } else if(c.getInt(columnStatus) == DownloadManager.STATUS_FAILED) { 
           // TODO - Take appropriate action. Error in downloading one of the 
           // files. 
           return; 
          } 
         } 

         c.close(); 

         // calculate the progress to show ... 
         float progress = (filesDownloaded + fileFracs)/ids.length; 

         // setting the progress text and bar... 
         final int percentage = Math.round(progress * 100.0f); 
         final String txt = "Loading ... " + percentage + "%"; 

         // Show the progress appropriately ... 
        } 
       } 
      } 
     }); 

     mProgressThread.start(); 
    } 

而要排隊到文件的功能是:

public static long addFileForDownloadInBkg(Context context, String url, String savePath) { 
     Uri uri = Uri.parse(url); 
     DownloadManager.Request request = new DownloadManager.Request(uri); 
     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); 
     request.setDestinationUri(Uri.fromFile(new File(savePath))); 

     final DownloadManager m = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); 
     return m.enqueue(request); 
    } 

基本上,我個人收到相關通知各已經完成下載的文件,然後將它們添加到基本上可以幫助我決定是否所有下載已完成的集合中。我根據文件數量和每個完成的部分來跟蹤進度。我希望這有幫助。