** 我正在尝试向我的应用程序添加警报以触发通知,问题是,每当我添加新警报时,前一个警报都不起作用。我想是因为request code passed(所有的alarm都有相同的code(0)),但是不知道怎么每次都传一个新的request code。 **
这是我的 setAlarm() 函数:
private fun setAlarm() {
alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlarmReceiver::class.java)
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calender.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
Toast.makeText(this, "alarm set", Toast.LENGTH_SHORT).show()
}
这是我的警报接收器类:
private lateinit var pendingIntent: PendingIntent
override fun onReceive(p0: Context?, p1: Intent?) {
val intent = Intent(p0, MainActivity::class.java)
p1!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
pendingIntent = PendingIntent.getActivity(p0, 0, intent, 0)
val builder = NotificationCompat.Builder(p0!!, "androidAlarm")
.setSmallIcon(drawable.notification_bg)
.setContentTitle("Your reminder!")
.setContentText("Your work has to be done now!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(pendingIntent)
val notificationManager = NotificationManagerCompat.from(p0)
if (ActivityCompat.checkSelfPermission(
p0,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return
}
notificationManager.notify(123, builder.build())
}
}
**如果用户愿意,我也不知道如何重复警报。
***我尝试在请求代码参数中使用 System.currentTimeMillis(),但没有帮助。
我搜索了很多但没有找到多少。*****