繁体   English   中英

Android 通知回调

[英]Android notification callback

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

我感到困惑的是如何让回调在原来的 class 中执行某些操作。 理想情况下,最好有类似的东西:

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 是为了打开一个新的意图,而不是在打开它的 class 上调用 function? 有没有办法做到这一点?


编辑:好的,我发现了如何从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 来创建其通知,但我注意到有时当我 select 状态下拉列表中的通知时,它使用错误的 Z527114E215E8 调用 DownloadService和标题,几乎就像它在使用另一个通知的 ID? 如何解决这个问题?

我终于找到了为什么通知不起作用。 在我制作的通知 class 中,“新的 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);

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

取消任务:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM