Skip to content

Instantly share code, notes, and snippets.

@waliahimanshu
Last active August 26, 2019 19:57
Show Gist options
  • Save waliahimanshu/f927a9c1745bdd226320630d9fe996ee to your computer and use it in GitHub Desktop.
Save waliahimanshu/f927a9c1745bdd226320630d9fe996ee to your computer and use it in GitHub Desktop.
internal const val ARG_ID_KEY = "ALARM_ID_KEY"
internal const val ARG_REQUEST_CODE_KEY = "ALARM_REQUEST_CODE_KEY"
internal const val ARG_ALARM_TYPE = "ARG_ALARM_TYPE"
/**
* @param appContext injected via DI
*/
class AlarmWrapperImp(private val appContext: Context) : AlarmWrapper {
private var alarmManager: AlarmManager? = null
private lateinit var alarmIntent: PendingIntent
init {
alarmManager = appContext.getSystemService(Context.ALARM_SERVICE) as? AlarmManager
}
override fun setAlarm(alarmType: AlarmType, requestCode: String, id: String) {
alarmIntent = Intent(appContext, AlarmReceiver::class.java).let { intent ->
intent.putExtra(ARG_ID_KEY, id)
intent.putExtra(ARG_REQUEST_CODE_KEY, requestCode)
intent.putExtra(ARG_ALARM_TYPE, alarmType.name)
// PendingIntent.getBroadcast(appContext, 1, intent, 0) Bug : I used same same request code for both alarms
PendingIntent.getBroadcast(appContext, requestCode, intent, 0)
}
when (alarmType) {
AlarmType.TYPE1 -> {
alarmManager?.set(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60 * 1000, // Wake up the device to fire a one-time (non-repeating) alarm in one minute
alarmIntent
)
}
AlarmType.TYPE2 -> {
alarmManager?.set(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 300 * 1000, // 5 minutes
alarmIntent
)
}
AlarmType.UNKNOWN -> throw IllegalArgumentException("unknown {${alarmType.name}} received")
}
}
override fun cancelAlarm(alarmType: AlarmType, requestCode: String, id: String) {
alarmIntent = Intent(appContext, AlarmReceiver::class.java).let { intent ->
intent.putExtra(ARG_ID_KEY, id)
intent.putExtra(ARG_REQUEST_CODE_KEY, requestCode)
intent.putExtra(ARG_ALARM_TYPE, alarmType.name)
// to cancel the alarm, we need a same id.
PendingIntent.getBroadcast(appContext, requestCode, intent, 0)
}
alarmManager?.cancel(alarmIntent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment