6

我正在使用DownloadManager處理我的應用程序中的下載,我想在下載完成時通知用戶。Android - DownloadManager/BroadcastReceiver多次調用

我使用的是如下因素代碼工作良好

public void downloaddownload(View v){ 
     View v2 = (View) v.getParent(); 
     TextView urlView = (TextView) v2.findViewById(R.id.url); 
     String urlString = (String) urlView.getText().toString(); 
     TextView artistView2 = (TextView) v2.findViewById(R.id.artist); 
     final String artistString = (String) artistView2.getText().toString(); 
     TextView titleView2 = (TextView) v2.findViewById(R.id.title); 
     final String titleString = (String) titleView2.getText().toString(); 

     DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlString)); 
     request.setDescription(titleString); 
     request.setTitle(artistString); 
     // in order for this if to run, you must use the android 3.2 to compile your app 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      request.allowScanningByMediaScanner(); 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
     } 
     request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC + "/folder", titleString + " - " + artistString + ".mp3"); 

     Toast.makeText(mainContext, "Downloading " + titleString + " - " + artistString, Toast.LENGTH_SHORT).show(); 

     // get download service and enqueue file 
     DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
     manager.enqueue(request); 

     onComplete = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       // TODO Auto-generated method stub 
       Toast.makeText(mainContext, "Download \" " + titleString + " - " + artistString + "\" completed", Toast.LENGTH_LONG).show(); 
      } 
     }; 

     registerReceiver(onComplete, new IntentFilter(
        DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 


    } 

的問題是的onReceive方法被調用以前下載過。

假設我下載a.mp3,b.mp3和c.mp3,當a.mp3完成時我收到a.mp3完成,當b.mp3完成時我收到a.mp3完成,然後一個新的吐司b.mp3完成...

我怎麼能阻止呢?謝謝。

+0

下載管理器也有問題。另請參見http://stackoverflow.com/questions/10852821/downloadmanager-sends-status-successful-for-failed-download –

+0

在您的BroadcastReceiver onReceive方法你需要註冊像Activity.this.unregister(這個) – Gugelhupf

回答

9

呦註冊BroadcastReceiver每次你下載一個文件。這意味着,您第二次下載文件時,您將註冊兩個接收器。工作完成後,您應該使用unregisterReceiver()取消註冊(可能在onReceive())。

+0

我也有也是問題。 TNX – RedFlow

1
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
Query query = new Query(); 
query.setFilterById(downloadId); 
Cursor cur = manager.query(query); 
    if (cur.moveToFirst()) { 
     int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS); 
     if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) { 
      titleString=cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_TITLE));} 

你應該使用它來獲得你的標題字符串的個人下載。因爲每個下載都有自己的ID。我知道答案太晚了,但它可能有助於未來的其他人...