2017-04-20 71 views
0

我正在使用Android下載管理器類。在所有下載完成後,我需要編寫「下載完成」。我嘗試了一些東西,它的工作。但是在這裏它是在文件完成後寫入文件。我只需要寫一次(畢竟完成了)。我也嘗試沒有遊標。但我未能實現。如何從Android下載管理器完成所有下載後通知

public class DownloadReceiver extends BroadcastReceiver { 


Context context; 
@Override 
public void onReceive(Context context, Intent intent) { 
    long receivedID = intent.getLongExtra(
      DownloadManager.EXTRA_DOWNLOAD_ID, -1L); 
      DownloadManager mgr = (DownloadManager) 
      context.getSystemService(Context.DOWNLOAD_SERVICE); 

    DownloadManager.Query query = new DownloadManager.Query(); 
    query.setFilterById(receivedID); 
    Cursor cur = mgr.query(query); 
    int index = cur.getColumnIndex(DownloadManager.COLUMN_STATUS); 
    if(cur.) { 
     String filePath = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_TITLE)); 
     if(cur.getInt(index) == DownloadManager.STATUS_SUCCESSFUL){ 
      DatabaseHandler dh = new DatabaseHandler(context); 
      dh.addDownloadComplete(new DownloadComplete("Download Complete")); 
     } 
    } 
    cur.close(); 
}} 
+0

所有下載完成後,你的意思是什麼?你是否有一組下載ID要檢查它們是否完整,或者你只是想檢查DownloadManager中的每個下載(無論它是否來自你的應用)是否完成? –

+0

我正在從列表中下載文件。在上面的例子中,它逐個檢查,然後寫下載逐個完成。但我需要的是,下載完所有文件後,我需要寫下載完成一次。 – venura

回答

1

在通知所有下載完成之前添加檢查。像

query.setFilterByStatus(DownloadManager.STATUS_PAUSED | 
     DownloadManager.STATUS_PENDING | 
     DownloadManager.STATUS_RUNNING); 
    Cursor cursor = downloadManager.query(query); 
    if (cursor != null && cursor.getCount() > 0) { 
     return; 
    }else { 
     query.setFilterById(receivedID); 
     //proceed your... 
    } 
+0

此解決方案的問題是可能存在由其他應用程序啓動的下載(暫停,掛起或正在運行)。此外它不檢查下載是否失敗。 –

+0

註冊接收機<接收機 機器人:名稱= 機器人 「receiver.DownloadBroadcastReceiver。」:導出= 「真」> <意圖濾波器> <操作機器人:名稱= 「android.intent.action.DOWNLOAD_COMPLETE」/> 這工作正常。爲您的確認下載其他應用程序的任何文件。 –

0

這是我認爲會工作。定義一個函數如下:

public boolean areAllDownloadsComplete(int[] downloadIds) { 

    DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); 

    DownloadManager.Query query = new DownloadManager.Query(); 

    for(int i = 0; i < downloadIds.length; i++) { 

     query.setFilterById(downloadIds[i]); 

     Cursor cur = mgr.query(query); 

     if(cur.moveToNext()) { 

      if(cur.getInt(cur.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL) { 

       return false; 
      } 
     } 
    } 

    return true; 
} 

呼叫廣播裏面這個功能(在每次下載完成通知),如下所示:

if(areAllDownloadsComplete(THE_DOWNLOAD_IDS)) { 
    DatabaseHandler dh = new DatabaseHandler(context); 
    dh.addDownloadComplete(new DownloadComplete("Download Complete")); 
} 

您可以通過下載IDS到您的廣播接收器的意圖是

Bundle bundle = new Bundle(); 
bundle.putIntArray("download_ids", THE_DOWNLOAD_IDS); 
intent.putExtra(bundle);