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

时间:2015-01-09 20:31:20

标签: android notifications push-notification android-notifications notificationmanager

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

@SuppressWarnings("弃用&#34)     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);
}

此代码中缺少什么?

2 个答案:

答案 0 :(得分:0)

对我来说很好看。我的自动取消仍适用于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());
}

答案 1 :(得分:0)

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

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

如果您想设置特殊条件,可以通过

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