Skip to content

Commit

Permalink
Fixed bug: random time coercing
Browse files Browse the repository at this point in the history
  • Loading branch information
lhwdev committed Nov 27, 2021
1 parent 1f136d8 commit 7697012
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
29 changes: 18 additions & 11 deletions app/src/main/java/com/lhwdev/selfTestMacro/selfTestUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ suspend fun Context.submitSuspend(session: Session, notification: Boolean = true
)
)

pref.lastSubmitDay = millisToDaysCumulative(Date().time)
pref.lastSubmit = Date().time

selfLog("submitSuspend success ${pref.user?.identifier?.mainUserName} ${result.registerAt}", force = true)

Expand Down Expand Up @@ -117,33 +117,40 @@ fun Context.scheduleNextAlarm(
) {
val pref = preferenceState

val newTime = Calendar.getInstance().run {
val newMin = if(isRandom) (min + random.nextInt(-5, 6)).coerceIn(0, 59) else min
var newTime = Calendar.getInstance().run {
val new = clone() as Calendar
new[Calendar.HOUR_OF_DAY] = hour
new[Calendar.MINUTE] = newMin
new[Calendar.SECOND] = 0
new[Calendar.MILLISECOND] = 0

// Submitted today
if(nextDay || pref.lastSubmitDay == millisToDaysCumulative(new.timeInMillis)) {
val last = pref.lastSubmit
val lastDay = millisToDaysCumulative(last)
if(nextDay || lastDay == millisToDaysCumulative(new.timeInMillis) ||) {
new.add(Calendar.DAY_OF_YEAR, 1)
}

new[Calendar.HOUR_OF_DAY] = hour
new[Calendar.MINUTE] = min
new[Calendar.SECOND] = 0
new[Calendar.MILLISECOND] = 0
new
}.timeInMillis

if(isRandom) {
newTime += 1000 * 60 * (Random.nextFloat() * 5).toInt()
}
selfLog("scheduling next alarm at ${Date(newTime.timeInMillis)}", force = true)

selfLog("scheduling next alarm at ${Date(newTime)}", force = true)

val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
if(Build.VERSION.SDK_INT < 21) {
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
newTime.timeInMillis,
newTime,
intent
)
} else {
alarmManager.setAlarmClock(
AlarmManager.AlarmClockInfo(
newTime.timeInMillis,
newTime,
PendingIntent.getActivity(
this,
0,
Expand Down
6 changes: 3 additions & 3 deletions app/src/main/java/com/lhwdev/selfTestMacro/utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,10 @@ class PreferenceState(val pref: SharedPreferences) {
var setting: UserSetting?
by pref.preferenceSerialized("userSetting", UserSetting.serializer())

var lastSubmitDay: Long
get() = pref.getLong("lastSubmitDay", Long.MIN_VALUE)
var lastSubmit: Long
get() = pref.getLong("lastSubmit", Long.MIN_VALUE)
set(value) = pref.edit {
putLong("lastSubmitDay", value)
putLong("lastSubmit", value)
}

var lastQuestion: String? by pref.preferenceString("lastQuestion")
Expand Down

0 comments on commit 7697012

Please sign in to comment.