Last active
August 26, 2019 19:57
-
-
Save waliahimanshu/f927a9c1745bdd226320630d9fe996ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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