android - 通知自动取消不适用于 Android Lollipop

标签 android notifications push-notification android-notifications notificationmanager

我想在用户点击通知时自动取消我的通知。以下代码适用于除 Android Lollipop 设备以外的所有设备。在 Lollipop 设备中,仅当用户将其滑动关闭时才会发出通知。

@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());
}

关于android - 通知自动取消不适用于 Android Lollipop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27868742/

相关文章:

android - 除了交叉编译 (Titanium) 和混合 (PhoneGap) 之外,开发跨平台应用程序的有效方法

android - 仅位图 TileX

ios - 如何通过 FCM(Firebase) 或 native 在 iOS 10 中发送推送通知?

android - 覆盖每个 Activity 的 Activity 转换

android - 隐藏软键盘

php - OneSignal 群组通知

ios - 如何在 iOS 中监听传入的短信事件

ios - 如果应用程序位于前台,则单击本地通知时打开特定 View Controller ?

iOS 有什么方法可以在收到推送通知警报消息后对其进行修改?

php - 如何使用触发器发送 firebase 推送通知