如何解决Android通知回调
| 我正在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- Android上的asynctask / 我很困惑的是如何使回调在调用它的原始类中执行某些操作。理想的情况是,有这样的东西: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是为了打开新的intent而创建的,而不是在打开它的类上调用了一个函数?有什么办法吗?
编辑:好的,我发现了如何从未决的意图中调用呼叫服务:
Intent returnIntent = new Intent(_context,DownloadService.class);
returnIntent.putExtra(\"url\",_url);
returnIntent.putExtra(\"name\",_title);
notificationIntent = PendingIntent.getService(_context,returnIntent,0);
notification.setLatestEventInfo(_context,_title,_url,notificationIntent);
由于始终只运行一个服务,因此DownloadService的所有AsyncTasks都有一个ArrayList,并且onStart检查其中一个是否具有相同的url和标题,如果是,则调用AsyncTask的方法来取消运行项或对已完成的项目执行操作。
ArrayList的计数作为新DownloaderTasks的ID发送,因此每个ID都有一个唯一的ID来创建其通知,但是我注意到有时当我在状态下拉列表中选择一个通知时,它会使用错误的URL调用DownloadService和标题,就像使用另一个通知的ID一样?如何解决?
解决方法
我终于找到了为什么通知不起作用的原因。在我创建的Notification类中,“新的PendingIntent”不足以创建新的PendingIntent。如文档中所述:
\“如果创建的应用程序以后重新检索相同类型的PendingIntent(相同的操作,相同的Intent操作,数据,类别和组件以及相同的标志),则它将收到代表相同令牌的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,returnIntent,PendingIntent.FLAG_CANCEL_CURRENT);
, 请参阅尝试取消执行AsyncTask的“ 3”方法。
取消任务:
https://developer.android.com/reference/android/os/AsyncTask.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。