Android – Как обновить номер уведомления

Привет, я хочу показать все уведомления в одном представлении ... и хочу обновить номер уведомления в строке состояния ... он обновляет всю информацию, но всегда показывает номер 1 ... пожалуйста, скажите мне, как это решить ...

@Override
public void onReceive(Context context, Intent intent)
{
    //Random randGen = new Random();
    //int notify_id = randGen.nextInt();
    NotificationManager notificationManager = (NotificationManager)
        context.getSystemService(Activity.NOTIFICATION_SERVICE);
    String title = intent.getStringExtra(TableUtils.KEY_TITLE);
    String occasion = intent.getStringExtra(TableUtils.KEY_OCCASION);
    Notification notification = 
        new Notification(R.drawable.icon, "Love Cardz" , 
                         System.currentTimeMillis());
    // notification.vibrate = new long[]{100,250,300,330,390,420,500};
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.number+=1;
    Intent intent1 = new Intent(context, ThemesBrowserActivity.class);
    PendingIntent activity = 
        PendingIntent.getActivity(context, 1 , intent1, 
                                  PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, occasion, title, activity);
    notificationManager.notify(1, notification);
}

person DkPathak    schedule 23.09.2012    source источник


Ответы (3)


Вы должны следить за счетом. Вы можете расширить класс приложения:

public class AppName extends Application {
    private static int pendingNotificationsCount = 0;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public static int getPendingNotificationsCount() {
        return pendingNotificationsCount;
    }

    public static void setPendingNotificationsCount(int pendingNotifications) {
        pendingNotificationsCount = pendingNotifications;
    }
}

И вы должны изменить onReceive:

@Override
public void onReceive(Context context, Intent intent) {
    ...
    int pendingNotificationsCount = AppName.getPendingNotificationsCount() + 1;
    AppName.setPendingNotificationsCount(pendingNotificationsCount);
    notification.number = pendingNotificationsCount;
    ...
}

И вы можете сбросить счетчик, когда пользователь откроет уведомление:

AppName.setPendingNotificationsCount(0);
person Andrea Motto    schedule 17.02.2013
comment
Довольно нелепо, что в фреймворке нет простого вызова getNotifications(int id), чтобы просто проверить это... - person LyteSpeed; 11.07.2014
comment
К сожалению, если приложение было убито, счетчик сбрасывается... Вероятно, следует сохранить в SharedPreference для сохранения - person xnagyg; 11.05.2015
comment
Как узнать, когда было открыто уведомление для сброса счетчика...? - person Micro; 11.03.2016
comment
@MicroR, вам нужно поместить класс Activity как часть вашего намерения в файл PendingIntent. stackoverflow.com/questions/7184963 / - person Andrea Motto; 11.03.2016
comment
Итак, вы говорите, что в onCreate() или что-то в Activity я должен сбросить счетчик? Я надеялся, что есть способ сделать это не так. - person Micro; 11.03.2016

Это мой код, и он работает. Я тестировал только на старых версиях Android тыс. Я подозреваю, что в более новых версиях значок «число» стал невидимым, но у меня не было возможности проверить это.

void notifyMsgReceived(String senderName, int count) {
    int titleResId;
    String expandedText, sender;

    // Get the sender for the ticker text
    // i.e. "Message from <sender name>"
    if (senderName != null && TextUtils.isGraphic(senderName)) {
        sender = senderName;
    }
    else {
        // Use "unknown" if the sender is unidentifiable.
        sender = getString(R.string.unknown);
    }

    // Display the first line of the notification:
    // 1 new message: call name
    // more than 1 new message: <number of messages> + " new messages"
    if (count == 1) {
        titleResId = R.string.notif_oneMsgReceivedTitle;
        expandedText = sender;
    }
    else {
        titleResId = R.string.notif_missedCallsTitle;
        expandedText = getString(R.string.notif_messagesReceivedTitle, count);
    }

    // Create the target intent
    final Intent intent = new Intent(this, TargetActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final PendingIntent pendingIntent =
        PendingIntent.getActivity(this, REQUEST_CODE_MSG_RECEIVED, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Build the notification
    Notification notif = new Notification(
        R.drawable.ic_notif_msg_received,  // icon
        getString(R.string.notif_msgReceivedTicker, sender), // tickerText
        System.currentTimeMillis()); // when
        notif.setLatestEventInfo(this, getText(titleResId), expandedText, pendingIntent);
    notif.number = count;
    notif.flags = Notification.FLAG_AUTO_CANCEL;

    // Show the notification
    mNotificationMgr.notify(NOTIF_MSG_RECEIVED, notif);
}

Также легко обновить уведомление позже: вам просто нужно снова вызвать метод с новыми значениями. Число будет отображаться на значке значка уведомления тогда и только тогда, когда оно было больше нуля при создании уведомления.

Точно так же значок номера не будет скрыт (число будет, тысяча), если вы установите число меньше 1. Возможно, очистка уведомления перед его повторным отображением может исправить это.

person rock3r    schedule 09.10.2012

Вы должны следить за счетом. Приращение, которое вы пытаетесь выполнить для notif.number, не работает, поскольку это состояние недоступно (т. е. notif.number всегда равно 0, затем вы увеличиваете его до 1). Отслеживайте число где-то в своем приложении (возможно, общие настройки), увеличивайте и сохраняйте его там, а затем, когда вы создаете уведомление, установите

notif.number = myStoredValueForWhatShouldShowInNumber;

Попробуйте.

person Travis    schedule 19.11.2012
comment
как сбросить номер, когда новое уведомление приходит с другим идентификатором уведомления - person Aditya Jaitly; 24.11.2020