1

Android N在下載管理器通知中有一個新的取消按鈕。Android N - 下載管理器通知取消按鈕

我想在我的應用程序中優先執行一些代碼,以便在用戶按下此按鈕時停止進度條。如果有的話,哪個方法被調用?

請注意,僅當用戶單擊通知本身時,才觸發Intent過濾器動作DownloadManager.ACTION_NOTIFICATION_CLICKED,而不是當他/她單擊取消按鈕時觸發。

if_downloadManager = new IntentFilter(); 
    if_downloadManager.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE); 
    if_downloadManager.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED); 

    br_downloadManager = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 

      if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
       .... 
      } 

      if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) { 
       // This code is not executed when the user presses the Cancel Button in the Download Manager Notification 
      }  
     } 
    }; 

在此先感謝。

+0

你找到一個解決辦法?我也有同樣的問題。 – Malko

回答

0

Malko,我沒有找到解決方案,但我正在使用以下解決方法。 我使用Android處理程序來運行,下面每10秒resetProgressIfNoOngoingDMRequest():

public int numberOfOngoingDMRequest() { 
    cursor = downloadManager.query(new Query()); 
    int res = cursor.getCount(); 
    cursor.close(); 
    return res; 
} 

public boolean resetProgressIfNoOngoingDMRequest() { 
    if (numberOfOngoingDMRequest() == 0) { 
     refreshUpdateAllButton(false); 
     resetEpisodesDownloadIds(); 
     act.misc.notifyEpisodesDataSetChanged(); 
     return true; 
    } 
    return false; 
} 

不是很好,但它的工作。我只在應用程序處於前臺時才這樣做。

0

另一種解決方案是使用ContentObserver

下載管理器的內容uri應該是content://downloads/my_downloads,我們可以監視這個數據庫的變化。當您使用下載ID開始下載時,將會創建一行content://downloads/my_downloads/{downloadId}。我們可以檢查這個指針來知道這個任務是否被取消。如果返回的遊標爲空或空,則在數據庫中找不到記錄,此下載任務將被用戶取消。

 // get the download id from DownloadManager#enqueue 
     getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), 
       true, new ContentObserver(null) { 
        @Override 
        public void onChange(boolean selfChange, Uri uri) { 
         super.onChange(selfChange, uri); 
         if (uri.toString().matches(".*\\d+$")) { 
          long changedId = Long.parseLong(uri.getLastPathSegment()); 
          if (changedId == downloadId[0]) { 
           Log.d(TAG, "onChange: " + uri.toString() + " " + changedId + " " + downloadId[0]); 
           Cursor cursor = null; 
           try { 
            cursor = getContentResolver().query(uri, null, null, null, null); 
            if (cursor != null && cursor.moveToFirst()) { 
             Log.d(TAG, "onChange: running"); 
            } else { 
             Log.w(TAG, "onChange: cancel"); 
            } 
           } finally { 
            if (cursor != null) { 
             cursor.close(); 
            } 
           } 
          } 
         } 
        } 
       }); 

看到答案here