Удалить уведомление при нажатии (Не дублировать) [дублировать]

Этот вопрос, вероятно, был задан и до ответа. Тем не менее, есть еще одна проблема при настройке данных.

OP создает данные с помощью

d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", n = 5), rep("green", n = 5)))

. Это приводит к чередованию двух цветов

d
#    x  y   col
#1   1  1   red
#2   2  2 green
#3   3  3   red
#4   4  4 green
#5   5  5   red
#6   6  6 green
#7   7  7   red
#8   8  8 green
#9   9  9   red
#10 10 10 green 

Причина в том, что n не является определенным параметром для функции rep(). Согласно ?rep, действительными параметрами являются times, lenght.out и each.

Вероятно, OP означал

d <- data.frame(x = 1:10,
                y = 1:10,
                col = c(rep("red", 5), rep("green", 5)))

, что приводит к последовательным строкам окрашиваются в один цвет:

d
#    x  y   col
#1   1  1   red
#2   2  2   red
#3   3  3   red
#4   4  4   red
#5   5  5   red
#6   6  6 green
#7   7  7 green
#8   8  8 green
#9   9  9 green
#10 10 10 green

Кстати,

col = c(rep("red", 5), rep("green", 5))

можно более четко записать как

col = rep(c("red", "green"), each = 5)

При этом следующие операторы сюжета

library(ggplot2)
# variant 1 (OP's own answer)
ggplot(data = d, aes(x = x, y = y)) + geom_point(colour = d$col)
# variant 2 (aosmith' comment, more "ggplot2-like")
ggplot(data = d, aes(x = x, y = y, colour = col)) + geom_point() + 
  scale_colour_identity()

создают одну и ту же диаграмму:

40
задан user1756912 19 October 2012 в 12:12
поделиться

5 ответов

Используйте флаг Notification.FLAG_AUTO_CANCEL

Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent);

// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;

и для запуска приложения:

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

// Create a new intent which will be fired if you click on the notification
Intent intent = new Intent(context, App.class);

// Attach the intent to a pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, intent_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
73
ответ дан input 22 August 2018 в 22:23
поделиться
  • 1
    Спасибо, это сделало работу :) – user1756912 19 October 2012 в 12:20
  • 2
    Рад, что это помогло! :) – input 19 October 2012 в 12:22
  • 3
    Как насчет ситуации, когда вы не указываете ContentIntent (просто хотите, чтобы уведомление удалялось при нажатии)? В этом случае флаг auto_cancel, похоже, не помогает ... – Alex Semeniuk 24 October 2013 в 09:08
  • 4
    Отвечая на мой собственный комментарий: вы не можете этого сделать. Единственный способ добиться чего-то подобного - создать «пустой». PendingIntent .setContentIntent(PendingIntent.getActivity(context, id, new Intent () , PendingIntent.FLAG_CANCEL_CURRENT)); Однако уведомление о прослушивании также скроет панель уведомлений (вам нужно будет вернуть ее, если у вас есть много уведомлений, которые вам нужно очистить). – Alex Semeniuk 24 October 2013 в 09:15
  • 5
    ОШИБКА: флаги не могут быть разрешены или не являются полем – Prasad 29 December 2014 в 08:16

Чтобы получить тот же эффект, используя Notification.Builder или NotificationCompat.Builder вызов setAutoCancel(true) в экземпляре Builder.

96
ответ дан 0101100101 22 August 2018 в 22:23
поделиться

Лучший & amp; простой способ установлен builder.setAutoCancel(true), он отменяет ваше уведомление после нажатия на уведомление. Я надеюсь, что этот код вам поможет.

Builder для уведомления

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

Для открытия активности при нажатии уведомления

Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);

Показать имя в уведомлении

g3]
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());

Полный код для отображения уведомлений со значком, изображением, заголовком, описанием, автоматическим отменам и щелчком мыши открыть действие

public void ShowIntentNotification(View v)
    {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(android.R.drawable.btn_star);
        builder.setContentTitle("This is title of notification");
        builder.setContentText("This is a notification Text");
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

        Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);
        builder.setAutoCancel(true);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(114, builder.build());

    }
2
ответ дан AXN Unicode Technologies 22 August 2018 в 22:23
поделиться

Этот ответ слишком поздний, но особенно я пишу следующее решение, потому что конструктор уведомлений устарел, поэтому используйте уведомление с помощью построителя, например следующее:

 **.setAutoCancel(true)** is used to remove notification on click

, и полное уведомление похоже на следующее:

  private void makeNotification(String title,String msg){

    Intent resultIntent = new Intent(this, MasterActivity.class);

    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    this,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentIntent(resultPendingIntent)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle(title)
                    .setAutoCancel(true)
                    .setContentText(msg);

    int mNotificationId = 001;
    NotificationManager mNotifyMgr =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

}

Вызов этого метода с заголовком и сообщением вы получите отличное уведомление.

6
ответ дан Joseph Mekwan 22 August 2018 в 22:23
поделиться

Для меня это было то, что

.setPriority(Notification.PRIORITY_HIGH);

, из-за чего уведомление не очищалось после щелчка ... убедитесь, что вы используете:

.setPriority(Notification.PRIORITY_DEFAULT);

И .setAutoCancel(true) должен работать.

0
ответ дан NickPR 22 August 2018 в 22:23
поделиться
Другие вопросы по тегам:

Похожие вопросы: