我在 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?如何解决这个问题?