【发布时间】: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