通知自动取消不适用于安卓棒棒糖



我想在用户单击通知时自动取消通知。以下代码在除Android棒棒糖设备以外的所有设备上都运行良好。在棒棒糖设备中,仅当用户将其刷掉时,才会发出通知。

@SuppressWarnings("deprecation")
public void sendNotification(int id){
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Test")
            .setContentText("Jump to next screen")
            .setDefaults(Notification.DEFAULT_SOUND)
            .setAutoCancel(true);
    mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, NextActivity.class);
   resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, 
                                    resultIntent, 0);
    //PendingIntent.FLAG_UPDATE_CURRENT
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // id, if there is a need to update the notification later on.
    mNotificationManager.notify(id, mBuilder.build());
    Log.v(TAG, "Notification ID value " + id);
    //mNotificationManager.cancel(id);
}

此代码中缺少什么?

对我来说

看起来不错。我的自动取消仍然适用于 5.0.2。让我给你一部分我的代码:

public static void notif(int id, String title, String text, Context context, Class activity) {
    // get an instance of the NotificationManager service
    if (mNotifyMgr == null)
        mNotifyMgr = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent = new Intent(context, activity);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.launcher)
            .setContentTitle(title)
            .setContentText(text)
            .setContentIntent(notifIntent);
    mNotifyMgr.notify(id, mBuilder.build());
}

修改以下内容:setAutoCancel(true) -> setAutoCancel(false);然后在操作活动上执行以下操作

NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();

如果要设置特殊条件,可以通过以下方式设置

intent.putExtra("key", "value")

最新更新