用特定的额外内容创造多个意图,总是阅读相同的额外内容



我正在设置一个应用程序,其中包含一些由某些警报触发的通知。为了设置不同的通知,我将当前毫秒时间作为Id。然而,当我通过extra将其传递给intent时,它总是收到相同的值。

这是我的代码,它会更清晰:在mainActivity中,我们有:

class MainActivity : AppCompatActivity() {
private lateinit var alarmManager: AlarmManager
private lateinit var pendingIntent: PendingIntent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createNotificationChannel() //create a channel
}

//Set a notification that will be triggered in a given time in ms.
//you can pass a title/description and Id in parameter
private fun setNotification(timeMS: Long, title: String, description: String, id: Int){
alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val intent = Intent(this, ReminderBroadcastReceiver::class.java)
intent.putExtra("title", title)
intent.putExtra("description", description)
intent.putExtra("id", id)
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeMS, pendingIntent)
}
//this button trigger a basics notification in 1 sec
//here we use an id based on current time. We may use some parsed part of the corresponding deadline later.
fun triggerNotification(view:View) {
var id = System.currentTimeMillis().toInt()
setNotification(System.currentTimeMillis()+1000, "foo", "ouafouaf", id)
}

然后在ReminderBroadcastReceiver:

class ReminderBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var channelId = "remindersChannel"
var title = intent!!.getStringExtra("title")
var content = intent!!.getStringExtra("description")
var notifId = intent!!.getIntExtra("id", 0)
val intent2 = Intent(context, MainActivity::class.java)
intent2!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

val pendingIntent = PendingIntent.getActivity(context, 0, intent2, PendingIntent.FLAG_IMMUTABLE)
val notifBuilder = NotificationCompat.Builder(context!!, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title + notifId.toString())
.setContentText(content)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(notifId, notifBuilder.build())
}
}

我的问题是,如果我在不同的时间点击两次按钮,收到的id不会改变。当我把System.currentTimeMillis().toInt()直接放在notify的参数中时,它工作得很好。

知道怎么解决这个问题吗?

PendingIntent.getBroadcast((的第二个参数需要针对每个不同的通知而不同。

(只需使用CommonsWare的评论来回答并关闭此线程(

最新更新