Вот код, который устанавливает будильник:
Код: Выделить всё
val deleteIntent = Intent(context, AlarmReceiver::class.java).apply {
action = "com.example.ALARM_ACTION_DELETE"
putExtra("medicationIndex", medication.medicationIndex)
putExtra("uniqueID", medication.uniqueID)}
val deletePendingIntent = PendingIntent.getBroadcast(
context.applicationContext,
alarmID, // Using the same alarmID for the delete alarm
deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val endTime = System.currentTimeMillis() + (1 * 60 * 1000L) // Test with 1 minute
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
endTime,
deletePendingIntent
)
Код: Выделить всё
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
val medName = intent.getStringExtra("medName")
val quantity = intent.getStringExtra("quantity")
val uniqueID = intent.getIntExtra("uniqueID", -1)
if (action == "com.example.ALARM_ACTION_DELETE") {
val medicationIndex = intent.getIntExtra("medicationIndex", -1)
val uniqueID = intent.getStringExtra("uniqueID")
if (medicationIndex != -1 && uniqueID != null) {
// Logic to remove the alarm from SharedPreferences
val sharedPreferences = context.getSharedPreferences("medications", Context.MODE_PRIVATE)
val medications = MedicationUtils.getMedicationsFromSharedPreferences(sharedPreferences)
if (medicationIndex < medications.size) {
MedicationUtils.deleteMedication(context, medicationIndex, medications)
}
} else {
Log.e("AlarmReceiver", "Received empty data: medicationIndex or uniqueID is missing")
}
}
}
}
Код: Выделить всё
I verified that the values are not null before sending them in the Intent.
I made sure to use PendingIntent.FLAG_UPDATE_CURRENT to update the PendingIntent.
Подробнее здесь: https://stackoverflow.com/questions/792 ... dingintent