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