我的应用程序中有下载通知.我通过调用 addAction() 方法向 NotificationCompat.Builder 添加了取消"按钮.但按钮在 Android O 设备上不起作用.当我按下取消"按钮时,什么也没有发生.但是在 Android 上运行的按钮 <哦
I have download notification in my application. I've added "Cancel" button to NotificationCompat.Builder by calling addAction() method. But button not working on Android O device. When I press "Cancel" button nothing happens. But button working on Android < O.
我的通知:
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, channelId) .setContentTitle(title) .setSmallIcon(R.drawablework_download) .setContentText(contentText) .setOngoing(true) .setContentIntent(null) .addExtras(idBundle) .addAction(R.drawable.cancel, context.getString(R.string.cancel), getCancelPendingIntent(context, id)) .setProgress(100, 30, true);我的PendingIntent :
private PendingIntent getCancelPendingIntent(Context context, int id){ return PendingIntent.getBroadcast( context, id, new Intent("CANCEL_DOWNLOAD").putExtra("id", id), PendingIntent.FLAG_UPDATE_CURRENT); }我还有 NotificationReceiver :
public static class NotificationReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if ("CANCEL_DOWNLOAD".equals(action) && context != null){ int id = intent.getIntExtra("id", -1); NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (mgr != null) mgr.cancel(id); FtpManager.getInstance(new AppExecutors(), CredentialsManager.getInstance().getCredentials(context)) .cancelDownloading(); } } }在 Manifest 文件中我有:
<receiver android:name="eu.warble.pjapp.util.NotificationsManager$NotificationReceiver" android:exported="false"> <intent-filter> <action android:name="CANCEL_DOWNLOAD" /> </intent-filter> </receiver> 推荐答案Never 使用隐式 Intent 当显式 Intent 可以使用时.Android O 通过禁止从清单注册的接收器接收隐式 Intent 广播来帮助强制执行此操作.
Never use an implicit Intent when an explicit Intent will do. Android O helps enforce this by banning the receipt of implicit Intent broadcasts from manifest-registered receivers.
第 1 步:从 中删除 (这也意味着你可以去掉 android:export="false",因为这是现在的默认值)
Step #1: Remove the <intent-filter> from your <receiver> (which also means that you could get rid of android:exported="false", as that is now the default value)
第 2 步:将 new Intent("CANCEL_DOWNLOAD").putExtra("id", id) 替换为 new Intent(context, NotificationReceiver.class).putExtra("id", id)
Step #2: Replace new Intent("CANCEL_DOWNLOAD").putExtra("id", id) with new Intent(context, NotificationReceiver.class).putExtra("id", id)
更多推荐
PendingIntent 不适用于 Android O
发布评论