Skip to content

Instantly share code, notes, and snippets.

@DanishAmjad12
Created September 5, 2018 07:48
Show Gist options
  • Save DanishAmjad12/51ac394a3082ad10abe500725b7c082e to your computer and use it in GitHub Desktop.
Save DanishAmjad12/51ac394a3082ad10abe500725b7c082e to your computer and use it in GitHub Desktop.
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
/* enqueue the job */
AlarmJobIntentService.enqueueWork(context, intent)
}
companion object {
val CUSTOM_INTENT = "com.test.intent.action.ALARM"
val ctx = App.getInstance()
fun cancelAlarm() {
val alarm = ctx.getSystemService(Context.ALARM_SERVICE)
as AlarmManager
/* cancel any pending alarm */
alarm.cancel(pendingIntent)
}
@RequiresApi(Build.VERSION_CODES.M)
fun setAlarm(force: Boolean) {
cancelAlarm()
val alarm = ctx.getSystemService(Context.ALARM_SERVICE)
as AlarmManager
// EVERY N MINUTES
val delay = (1000 * 60 * N).toLong()
var `when` = System.currentTimeMillis()
if (!force) {
`when` += delay
}
/* fire the broadcast */
val SDK_INT = Build.VERSION.SDK_INT
when {
SDK_INT < Build.VERSION_CODES.KITKAT -> alarm.set(AlarmManager.RTC_WAKEUP, `when`, pendingIntent)
SDK_INT < Build.VERSION_CODES.M -> alarm.setExact(AlarmManager.RTC_WAKEUP, `when`, pendingIntent)
else -> alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, `when`, pendingIntent)
}
}
private val pendingIntent: PendingIntent
get() {
val alarmIntent = Intent(ctx, AlarmReceiver::class.java)
alarmIntent.action = CUSTOM_INTENT
return PendingIntent.getBroadcast(ctx, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment