安卓通知回调

标签 android notifications android-intent android-pendingintent

我在 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 是为了打开一个新的 Intent ,而不是在打开它的类上调用函数?有什么办法吗?


编辑:好的,我发现了如何从 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?如何解决?

最佳答案

我终于找到了通知不起作用的原因。在我制作的Notification类中,“new PendingIntent”不足以制作一个新的PendingIntent。如文档中所述: “如果创建应用程序稍后重新检索相同类型的 PendingIntent(相同操作、相同 Intent 操作、数据、类别和组件以及相同标志),它将如果它仍然有效,则接收表示相同 token 的 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);

关于安卓通知回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6192569/

相关文章:

angular - Electron 通知

swift - 如何从 GET 请求 Swift 获取通知

java - 如何仅在前一个对象完成时才从 Firebase 获取对象?

java - 如何使用 Picasso 在 Android 的 ViewPager 中加载图像

android - 如何使用 Cordova 创建子文件夹

ios - 类型 'UITextField' 没有成员 'textDidBeginEditingNotification'

android - 仅当空间足够时才在右侧查看,否则在底部

android - 如何通过 Android 中的 Intent 发送邮件?

c# - Private Set 属性不保留其新值

android-intent - Android API 30 getPackageManager.resolveActivity() 使用 ACTION_VIEW 返回 null