簡體   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