【发布时间】:2020-11-13 23:52:24
【问题描述】:
我有一个简单的 AsyncTask,它正在执行后台下载并使用通知向用户显示反馈。此外,此通知具有取消下载的操作。单击该操作后,应该发出广播,并且我的接收器类应该抓住它。但是,我无法单击该按钮:它似乎无法以任何方式进行交互。所有点击都属于通知本身。如果我在内容意图上设置 PendingIntent,它可以正常工作。
我正在运行 CyanogenMod Lollipop 5.0.2
这里是代码。
AndroidManifest.xml
<receiver android:name=".CancelReceiver">
<intent-filter>
<action android:name="org.warpten.dizzy.stopdownload"></action>
</intent-filter>
</receiver>
异步任务构造函数
public DownloaderTask(Context ctx, SearchMatch info) {
_context = ctx;
_info = info;
_notification = new Notification.Builder(_context);
_notificationManager = (NotificationManager)_context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent actionIntent = new Intent("org.warpten.dizzy.stopdownload");
actionIntent.putExtra("notificationId", _info.id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(_context, 0, actionIntent, PendingIntent.FLAG_ONE_SHOT);
_notification.setPriority(Notification.PRIORITY_MAX);
if (ImageCache.HasImage(_info.id))
_notification.setLargeIcon(ImageCache.GetImageBitmap(_info.id));
// _notification.setContentIntent(pendingIntent); // This works
_notification.addAction(android.R.drawable.ic_menu_close_clear_cancel,
"Cancel", pendingIntent); // Doesn't work, cannot interact with the action
}
经理可以在 doInBackground 中进一步通知通知。
广播接收器
public class CancelReceiver extends BroadcastReceiver {
interface ICancelReceiver
{
void CancelDownload(int trackId);
}
public static ICancelReceiver Listener; // Lazyness to write a setter
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", -1);
if (Listener != null && notificationId != -1)
Listener.CancelDownload(notificationId);
}
}
【问题讨论】:
-
如果您在通知中有一个按钮并且您希望它可以点击。您应该使用 RemoteViews,这样您就可以在按下按钮时执行操作。
标签: android notifications broadcastreceiver