i working on an app that needs to set an alarm for a user specified period in the future.
now there are a lot of example out there so, should not be to hard should it 🙁
Now this is still not the most pretty code as in the use of resource.
To set the alarm
fun setAlarm(offsetDay: Int, hour: Int, min: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
Toast.makeText(mContext, "need min android O", Toast.LENGTH_LONG).show()
} else {
val alarmManager = mContext.getSystemService(AlarmManager::class.java)
val alarmIntent = Intent(mContext, CustomAlarmReceiver::class.java).let {
PendingIntent.getBroadcast(mContext, 222, it, PendingIntent.FLAG_IMMUTABLE) }
// todo: on the real phone version remove the timezone for the now-part it will then take the default timezone
val now = LocalDateTime.now(TimeZone.getTimeZone("Europe/Amsterdam").toZoneId())
val tempTarget = LocalDateTime.of(
now.toLocalDate(),
LocalTime.of(hour, min)
)
val target = tempTarget.plusDays(offsetDay.toLong())
val duration = Duration.between(now, target)
if (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
alarmManager.canScheduleExactAlarms()
} else {
true
}
) {
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + duration.toMillis(),
alarmIntent
)
Toast.makeText(mContext,"alarm set", Toast.LENGTH_LONG).show()
}
}
}
Now everything runs without any error but no alarm is set.
it is also hard to find if an alarm is set because examples where the create the intent with FLAG_NO_CREATE does not work over android 12 and i was not able to find another way to check this.
using the command “adb shell dumpsys alarm” gives so much data it is nearly impossible to find anything but after a long long search i am pretty sure my alarm is not in the list.
so 2 questions for now:
- what is wrong with my code to set an alarm?
- how do you check if “the” alarm is set in android above 12?
Hope somebody can help