【问题标题】:How to count number of notification and display single icon in Android?如何在Android中计算通知数量并显示单个图标?
【发布时间】:2011-06-17 03:54:52
【问题描述】:

我有多个 Android 通知,但是当我从我的网络服务器发送消息时,Android 设备会在状态栏上创建一个新的通知图标。我想计算未读通知的数量,用单个图标显示在statusbar,当一个通知被阅读时,通知必须改变未读通知的数量。我该怎么做?在这张图片中看起来像“3 Others”:Notification Icon

【问题讨论】:

    标签: android eclipse android-notifications android-notification-bar


    【解决方案1】:

    在这里查看答案:How to give counter if more than one Notifications are there

    你只需要设置Notification.number:

    Notification notification = new Notification(R.drawable.direction, "Cool Notification",
                    System.currentTimeMillis());
            /********LIKE THIS*********/
            notification.number = notificationCount++;
            /********LIKE THIS*********/
    
            notification.setLatestEventInfo(context, "Cool Notification Title",
                    "updated notificaiton message", null);
    
    
            NotificationManager nm = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            nm.notify(R.id.my_motification, notification);
    

    您必须通过NotificationManager.notify 方法发送您的通知,并且始终使用相同的ID。正如文档所说,id 是应用程序中该通知的唯一标识符。如果您重复使用相同的 id,它只会更新该通知的文本和编号。

    要检查用户何时点击通知,您需要提供 PendingIntent(请参阅tutorial)。要检查用户何时清除通知,您需要使用仅在 Api Level 11 中可用的Notification.Builder

    【讨论】:

    【解决方案2】:

    这些代码对我有用:

    Notification n = new Notification(R.drawable.yourownpicturehere, 
                                       getString(R.string.noticeMe), 
    
    System.currentTimeMillis());    
    PendingIntent i=PendingIntent.getActivity(this, 0,
                                               new Intent(this, NotifyActivity.class),0);
    
    n.setLatestEventInfo(getApplicationContext(), 
                         getString(R.string.title),
                         getString(R.string.message), i);
    n.number=++count;
    n.flags |= Notification.FLAG_AUTO_CANCEL;
    n.flags |= Notification.DEFAULT_SOUND;
    n.flags |= Notification.DEFAULT_VIBRATE;
    n.ledARGB = 0xff0000ff;
    n.flags |= Notification.FLAG_SHOW_LIGHTS;
    
    // Now invoke the Notification Service
    String notifService = Context.NOTIFICATION_SERVICE;
    NotificationManager mgr = (NotificationManager) getSystemService(notifService);
    mgr.notify(NOTIFICATION_ID, n);
    

    关注link 获取完整教程。
    我认为n.number=++count; 是负责统计通知的人

    【讨论】:

      【解决方案3】:

      您需要为每个数字使用不同的位图,并设置图标以显示与剩余通知数量相对应的位图。

      要跟踪通知,您可以简单地在 SharedPreferences 中设置一个计数器,在每个新通知中添加一个计数器,并在读取通知时减一(如果您一次显示所有通知,则减为零)。

      【讨论】:

      • @Aleadam:我已经在SharedPreferences中添加了计数器,但是我不知道如何确定通知是已读还是未读并设置计数器的值?我怎样才能捕捉到这个事件?
      • 有一种原生方式可以在 Android 上做到这一点,而无需使用您自己的位图。见stackoverflow.com/questions/7203541/…
      猜你喜欢
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 2017-03-12
      相关资源
      最近更新 更多