我的申请中有下载通知。我已通过调用NotificationCompat.Builder
方法向addAction()
添加了“取消”按钮。但按钮无法在Android O设备上运行。当我按“取消”按钮时没有任何反应。但按钮在Android上运行< O操作。
我的Notification
:
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, channelId)
.setContentTitle(title)
.setSmallIcon(R.drawable.network_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>
答案 0 :(得分:7)
从不在显式Intent
时使用隐式Intent
。 Android O通过禁止从清单注册的接收方接收隐式Intent
广播来帮助强制执行此操作。
第1步:从<intent-filter>
中移除<receiver>
(这也意味着您可以摆脱android:exported="false"
,因为这是默认值)
第2步:将new Intent("CANCEL_DOWNLOAD").putExtra("id", id)
替换为new Intent(context, NotificationReceiver.class).putExtra("id", id)
答案 1 :(得分:1)
非常感谢CommonsWare。这个对我有用。这是我的代码
var notifyIntent = Intent(context, NotificationBroadcastReceiver::class.java)
notifyIntent.action = "ACTION_UPDATE_BADGE"//hardcode in manifest
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// only for oreo and newer versions
notifyIntent = Intent(context, NotificationBroadcastReceiverAndroidO::class.java)
}
val pendingIntent = PendingIntent.getBroadcast(context, it, notifyIntent, PendingIntent.FLAG_ONE_SHOT)
清单中
<receiver android:name=".firebase.NotificationBroadcastReceiver">
<intent-filter>
<action android:name="ACTION_UPDATE_BADGE" />
</intent-filter>
</receiver>
<receiver android:name=".firebase.NotificationBroadcastReceiverAndroidO">
<!--Android O not working when having this code
<intent-filter>
<action android:name="ACTION_UPDATE_BADGE" />
</intent-filter>-->
</receiver>
创建2个课程:
open class NotificationBroadcastReceiver : BroadcastReceiver() {...}
open class NotificationBroadcastReceiverAndroidO : NotificationBroadcastReceiver() {/*do nothing*/}