繁体   English   中英

Android:获取通知的唯一ID

[英]Android: get unique ID of notification

我有一个for块,看起来像这样:

for(int counter = 0; counter < sList.size(); counter++){
            String s = sList.get(counter);
            Notification notification = new NotificationCompat.Builder(this).setContentTitle("Title").setContentText(s).setSmallIcon(R.drawable.ic_launcher).setContentIntent(pendingIntent).build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(counter, notification);
}

该块位于由警报管理器触发的服务中。 因此,在用户看到通知之前,这个块可能会被执行几次。 当某个内容添加到sList时重新执行此块时,它会覆盖当前通知,因为通知的ID是相同的。 我怎样才能防止这种情况发生? 我怎样才能每次都获得一个唯一的ID? 或者是否有可能避免整个ID部分,就像告诉android无论如何都必须显示通知,无论ID是什么?

提前致谢!

long time = new Date().getTime();
String tmpStr = String.valueOf(time);
String last4Str = tmpStr.substring(tmpStr.length() - 5);
int notificationId = Integer.valueOf(last4Str);

notificationManager.notify(notificationId, notif);

它获得当前的系统时间。 然后我只读了它的最后4位数。 我每次显示通知时都会使用它来创建唯一的ID。 因此,将避免获得相同或重置通知ID的可能性。

我相信你不应该立即为用户提供这么多通知。 您应该显示一个通知,整合有关事件组的信息,例如Gmail客户端。 为此目的使用Notification.Builder

NotificationCompat.Builder b = new NotificationCompat.Builder(c);
       b.setNumber(g_push.Counter)
        .setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.list_avatar))
        .setSmallIcon(R.drawable.ic_stat_example)
        .setAutoCancel(true)
        .setContentTitle(pushCount > 1 ? c.getString(R.string.stat_messages_title) + pushCount : title)
        .setContentText(pushCount > 1 ? push.ProfileID : mess)
        .setWhen(g_push.Timestamp)
        .setContentIntent(PendingIntent.getActivity(c, 0, it, PendingIntent.FLAG_UPDATE_CURRENT))
        .setDeleteIntent(PendingIntent.getBroadcast(c, 0, new Intent(ACTION_CLEAR_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT))
        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
        .setSound(Uri.parse(prefs.getString(
                SharedPreferencesID.PREFERENCE_ID_PUSH_SOUND_URI,
                "android.resource://ru.mail.mailapp/raw/new_message_bells")));

如果你仍然需要有很多状态栏通知,你应该在某个地方保存你的计数器的最后一个值,并像这样使用for循环:

    int counter = loadLastCounterValue();
    for(String s : sList){
            Notification notification = new NotificationCompat.Builder(this).setContentTitle("Title").setContentText(s).setSmallIcon(R.drawable.ic_launcher).setContentIntent(pendingIntent).build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(++counter, notification);
    }
    saveCounter(counter);

但正如我所说,我认为这是一个糟糕的解决方案,导致您的应用程序的用户体验不佳。

您只需在通知构建器中指定一个ID即可。
相同的id =通知的更新
不同的id =新通知。

此外,两个不同的应用程序可以使用相同的通知ID,它将产生2个不同的通知没有问题。 系统会查看id和应用程序的来源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM