PendingIntent不适用于Android O.

War*_*ble 6 android broadcastreceiver android-notifications android-pendingintent android-8.0-oreo

我在我的申请中有下载通知.我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);
Run Code Online (Sandbox Code Playgroud)

我的PendingIntent:

private PendingIntent getCancelPendingIntent(Context context, int id){
    return PendingIntent.getBroadcast(
            context, id, new Intent("CANCEL_DOWNLOAD").putExtra("id", id), PendingIntent.FLAG_UPDATE_CURRENT);
}
Run Code Online (Sandbox Code Playgroud)

我也有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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Manifest档案中我有:

<receiver
        android:name="eu.warble.pjapp.util.NotificationsManager$NotificationReceiver"
        android:exported="false">
        <intent-filter>
            <action android:name="CANCEL_DOWNLOAD" />
        </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

Com*_*are 8

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)