This repository was archived by the owner on Aug 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEggTimerViewModel.kt
218 lines (189 loc) · 6.91 KB
/
EggTimerViewModel.kt
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.eggtimernotifications.ui
import android.app.AlarmManager
import android.app.Application
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.os.SystemClock
import androidx.core.app.AlarmManagerCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.android.eggtimernotifications.R
import com.example.android.eggtimernotifications.receiver.AlarmReceiver
import com.example.android.eggtimernotifications.util.cancelNotifications
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class EggTimerViewModel(private val app: Application) : AndroidViewModel(app) {
private val timerLengthOptions: IntArray
private val notifyPendingIntent: PendingIntent
private val alarmManager = app.getSystemService(Context.ALARM_SERVICE) as
AlarmManager
private var prefs =
app.getSharedPreferences("com.example.android.eggtimernotifications",
Context.MODE_PRIVATE)
private val notifyIntent = Intent(app, AlarmReceiver::class.java)
private val _timeSelection = MutableLiveData<Int>()
val timeSelection: LiveData<Int>
get() = _timeSelection
private val _elapsedTime = MutableLiveData<Long>()
val elapsedTime: LiveData<Long>
get() = _elapsedTime
private var _alarmOn = MutableLiveData<Boolean>()
val isAlarmOn: LiveData<Boolean>
get() = _alarmOn
private lateinit var timer: CountDownTimer
init {
_alarmOn.value = PendingIntent.getBroadcast(
getApplication(),
REQUEST_CODE,
notifyIntent,
PendingIntent.FLAG_NO_CREATE
) != null
notifyPendingIntent = PendingIntent.getBroadcast(
getApplication(),
REQUEST_CODE,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
timerLengthOptions = app.resources.getIntArray(R.array.minutes_array)
//If alarm is not null, resume the timer back for this alarm
if (_alarmOn.value!!) {
createTimer()
}
}
/**
* Turns on or off the alarm
*
* @param isChecked, alarm status to be set.
*/
fun setAlarm(isChecked: Boolean) {
when (isChecked) {
true -> timeSelection.value?.let { startTimer(it) }
false -> cancelNotification()
}
}
/**
* Sets the desired interval for the alarm
*
* @param timerLengthSelection, interval timerLengthSelection value.
*/
fun setTimeSelected(timerLengthSelection: Int) {
_timeSelection.value = timerLengthSelection
}
/**
* Creates a new alarm, notification and timer
*/
private fun startTimer(timerLengthSelection: Int) {
_alarmOn.value?.let {
if (!it) {
_alarmOn.value = true
val selectedInterval = when (timerLengthSelection) {
0 -> SECOND * 10 //For testing only
else ->timerLengthOptions[timerLengthSelection] * MINUTE
}
val triggerTime = SystemClock.elapsedRealtime() +
selectedInterval
// TODO STEP 1.5 - Get an instance of NotificationManager and
// call sendNotification
// TODO STEP 1.10 - Remove the notification code
// val notificationManager = ContextCompat.getSystemService(app,
// NotificationManager::class.java
// ) as NotificationManager
//
// notificationManager.sendNotification(
// app.getString(R.string.timer_running), app)
// TODO END STEP 1.10
// TODO END STEP 1.5
// TODO STEP 1.15 - Call cancel notification
val notificationManager =
ContextCompat.getSystemService(
app,
NotificationManager::class.java
) as NotificationManager
notificationManager.cancelNotifications()
// TODO END STEP 1.15
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager,
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerTime,
notifyPendingIntent
)
viewModelScope.launch {
saveTime(triggerTime)
}
}
}
createTimer()
}
/**
* Creates a new timer
*/
private fun createTimer() {
viewModelScope.launch {
val triggerTime = loadTime()
timer = object : CountDownTimer(triggerTime, SECOND) {
override fun onTick(millisUntilFinished: Long) {
_elapsedTime.value = triggerTime -
SystemClock.elapsedRealtime()
if (_elapsedTime.value!! <= 0) {
resetTimer()
}
}
override fun onFinish() {
resetTimer()
}
}
timer.start()
}
}
/**
* Cancels the alarm, notification and resets the timer
*/
private fun cancelNotification() {
resetTimer()
alarmManager.cancel(notifyPendingIntent)
}
/**
* Resets the timer on screen and sets alarm value false
*/
private fun resetTimer() {
timer.cancel()
_elapsedTime.value = 0
_alarmOn.value = false
}
private suspend fun saveTime(triggerTime: Long) =
withContext(Dispatchers.IO) {
prefs.edit().putLong(TRIGGER_TIME, triggerTime).apply()
}
private suspend fun loadTime(): Long =
withContext(Dispatchers.IO) {
prefs.getLong(TRIGGER_TIME, 0)
}
private companion object {
private const val MINUTE: Long = 60_000L
private const val SECOND: Long = 1_000L
private const val REQUEST_CODE = 0
private const val TRIGGER_TIME = "TRIGGER_AT"
}
}