android - 如何让通知只在用户点击时消失

android -How to make notification disappear only when user clicked on it

这是我的通知代码:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    int icon = R.drawable.ic_launcher;
    CharSequence tickerText = "Ticker Text";
    long time = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, time);
    notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
    Context context = getApplicationContext();
    CharSequence contentTitle = "Title";
    CharSequence contentText = "Text";
    Intent notificationIntent = new Intent(this, FistActiivty.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    mNotificationManager.notify(1,notification);

如何让通知仅在用户单击时消失,我的意思是我不希望通知在用户单击清除按钮时消失

感谢

public static final int NOTIFICATION_ID = 1;

NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

Intent myintent = new Intent(this, "your activity name"); ex:mainactivity.class

        myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
                myintent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);


        mBuilder.setAutoCancel(true); // this method is use for disappear notification after tap on it .

mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

使用:

// This notification will not be cleared by swiping or by pressing "Clear all"
notification.flags |= Notification.FLAG_NO_CLEAR;

也很重要:

.setOngoing(true) //put this inside your notification builder

或使用:Notification.FLAG_ONGOING_EVENT;代替.setOngoing(true)

这应该能帮到你。