Repository navigation
Expand file tree
/
Copy pathStatsScreen.kt
More file actions
54 lines (47 loc) · 1.88 KB
/
Copy pathStatsScreen.kt
File metadata and controls
54 lines (47 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.habitflow.app.notification
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import java.util.Calendar
/**
* Schedules a daily repeating alarm for a habit reminder, and cancels it
* again when the reminder is removed or the habit is deleted.
*/
object NotificationScheduler {
fun schedule(context: Context, habitId: Long, habitName: String, hour: Int, minute: Int) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = buildPendingIntent(context, habitId, habitName)
val triggerTime = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
set(Calendar.SECOND, 0)
if (before(Calendar.getInstance())) {
add(Calendar.DAY_OF_YEAR, 1)
}
}
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
triggerTime.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent
)
}
fun cancel(context: Context, habitId: Long) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = buildPendingIntent(context, habitId, habitName = "")
alarmManager.cancel(pendingIntent)
}
private fun buildPendingIntent(context: Context, habitId: Long, habitName: String): PendingIntent {
val intent = Intent(context, ReminderReceiver::class.java).apply {
putExtra(ReminderReceiver.EXTRA_HABIT_ID, habitId)
putExtra(ReminderReceiver.EXTRA_HABIT_NAME, habitName)
}
return PendingIntent.getBroadcast(
context,
habitId.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}