【问题标题】:Android notification callback安卓通知回调
【发布时间】:2011-05-31 19:30:27
【问题描述】:

我在 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/

我感到困惑的是如何让回调在调用它的原始类中执行某些操作。最好有类似的东西:

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);

由于始终只有一个服务在运行,DownloadService 有一个包含所有 AsyncTask 的 ArrayList,onStart 会检查其中一个是否具有相同的 url 和标题,如果是,则调用 AsyncTask 的方法取消正在运行的项目或对已完成的项目执行操作。

ArrayList 的计数作为新 DownloaderTasks 的 id 发送,因此每个都有一个唯一的 id 来创建其通知,但我注意到有时当我在状态下拉列表中选择通知时,它会调用 DownloadService错误的 url 和标题,几乎就像它使用另一个通知的 ID?如何解决这个问题?

【问题讨论】:

  • 您的问题似乎令人困惑。你想取消 AsyncTask 吗?你能提供一个你想做的例子吗?
  • 是的,我希望下载可以取消,类似于默认浏览器的下载器,如果已下载,您可以点击它取消或打开文件。

标签: android notifications android-intent android-pendingintent


【解决方案1】:

我终于找到了通知不起作用的原因。在我制作的 Notification 类中,“new 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, 0, returnIntent, PendingIntent.FLAG_CANCEL_CURRENT);

【讨论】:

【解决方案2】:

请参阅cancel(boolean) 方法,该方法尝试取消 AsyncTask 的执行。

取消任务:

https://developer.android.com/reference/android/os/AsyncTask.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 2017-12-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多