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/

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

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 和 title,如果是,它会调用 AsyncTask 的方法来取消正在运行的项目或执行操作在已完成的项目上。

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

4

2 回答 2

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);
于 2011-06-13T17:27:49.400 回答
0

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

取消任务:

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

于 2011-05-31T20:40:10.247 回答