1

我使用的AsyncTask本教程與任務和通知: https://eliasbland.wordpress.com/2011/03/11/an-example-of-how-to-run-a-background-task-and-report-progress-in-the-status-bar-using-asynctask-on-android/Android的通知回調

我感到困惑的是如何讓一個回調做一些原班它是從調用。理想情況下,這將是巨大的,有這樣的:

private class DownloaderTask extends AsyncTask { 
    doInBackground() { ... download the file ... } 

    onProgressUpdate, onPreExecute, etc. from the example, managing a notification. 

    notificationClicked() { 
     if (success) { 
      //show file 
     } else { 
      cancel(true); 
     } 
} 
但是

,看來的PendingIntent由打開新的意圖,不要稱呼打開它的類的功能?有沒有辦法做到這一點?


編輯:好吧,我發現瞭如何調用從的PendingIntent調用服務:

Intent returnIntent = new Intent(_context,DownloadService.class); 
returnIntent.putExtra("url", _url); 
returnIntent.putExtra("name",_title); 
notificationIntent = PendingIntent.getService(_context, 0, returnIntent, 0); 
notification.setLatestEventInfo(_context, _title, _url, notificationIntent); 

由於始終只有一個服務運行後,下載服務有其所有AsyncTasks的ArrayList,和onStart檢查其中一個是否具有相同的url和title,如果是,則調用AsyncTask的方法來取消正在運行的項目或對完成的項目執行操作。

ArrayList的計數是作爲新的DownloaderTasks的ID發送的,所以每個人都有一個唯一的ID來創建它的通知,但我注意到有時當我在狀態下拉列表中選擇一個通知時,它會調用DownloadService與錯誤的網址和標題,幾乎就像它使用另一個通知的ID?這怎麼解決?

+0

你的問題顯得撲朔迷離。你想取消AsyncTask嗎?你能提供一個你想要做什麼的例子嗎? – advantej 2011-05-31 20:06:49

+0

是的,我希望下載是可以取消的,就像默認瀏覽器的下載器一樣,你可以點擊它來取消或下載文件。 – NoBugs 2011-05-31 20:13:11

回答

1

我終於找到了爲什麼通知不工作。在我發佈的Notification類中,「新的PendingIntent」不足以創建新的PendingIntent。如文檔中所述: 「如果以後創建的應用程序重新檢索PendingIntent(相同操作,相同意圖操作,數據,類別和組件,以及相同標記)的同類,它將收到一個PendingIntent如果它仍然有效,則表示相同的標記,因此可以調用cancel()來移除它。「它還需要FLAG_CANCEL_CURRENT,因爲它可能會從前一次運行中緩存。

此代碼:

Intent returnIntent = new Intent(_context,DownloadService.class); 
returnIntent.putExtra("url", _url); 
returnIntent.putExtra("name",_title); 
returnIntent.putExtra("notifClick",true); 
returnIntent.setAction("test.test.myAction"+_NOTIFICATION_ID); 
// Important to make a unique action name, and FLAG_CANCEL_CURRENT, to make separate notifications. 

notificationIntent = PendingIntent.getService(_context, 0, returnIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
+0

和相同的requestCode,文檔聲明它是爲了將來使用,但它實際上用於相等性檢查。請參閱http://code.google.com/p/android/issues/detail?id=863 – 2012-07-25 10:32:35