Generate int unique id as android notification id

后端 未结 7 537
难免孤独
难免孤独 2020-12-05 16:37

When I send multiple push notifications, I need them to be all shown in the notification bar ordered by the time sent desc. I know I should use unique notification - I tried

相关标签:
7条回答
  • 2020-12-05 17:39

    You can use a counter and store it in the SharedPreferences. This is an example in kotlin:

    fun getNextNotificationId(context: Context) : Int {
        val sp = context.getSharedPreferences("your_shared_preferences_key", MODE_PRIVATE)
        val id = sp.getInt("notification_id_key", 0)
        sp.edit().putInt("notification_id_key", (id + 1) % Int.MAX_VALUE).apply()
    
        return id
    }
    

    it will get the id and it will store the next id (increased by 1), also if the id reaches the max value for an integer it will be reset to 0.

    You can use it like this:

    val notificationId = getNextNotificationId(applicationContext)
    notificationManager.notify(notificationId, yourNotification)
    
    0 讨论(0)
提交回复
热议问题