Skip to content

Instantly share code, notes, and snippets.

@SANDY-9
Last active April 18, 2024 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SANDY-9/3b496e57297853310e5794ad7e81b2d6 to your computer and use it in GitHub Desktop.
Save SANDY-9/3b496e57297853310e5794ad7e81b2d6 to your computer and use it in GitHub Desktop.
NotificationSchedulerImpl
import android.app.AlarmManager
import android.app.AlarmManager.AlarmClockInfo
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import com.sandy.seoul_matcheap.ui.more.settings.Time
import com.sandy.seoul_matcheap.util.constants.HOUR
import com.sandy.seoul_matcheap.util.constants.MINUTE
import java.util.Calendar
import javax.inject.Inject
const val NOTIFICATION_REQUEST_CODE = 0
class NotificationSchedulerImpl @Inject constructor(
private val context: Context,
private val alarmManager: AlarmManager
) : NotificationScheduler {
override fun schedule(time: Time) {
val dueTime = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, time.first)
set(Calendar.MINUTE, time.second)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
if(before(Calendar.getInstance())) add(Calendar.DATE, 1)
}
val intent = Intent(context, NotificationReceiver::class.java).apply {
putExtra(HOUR, time.first)
putExtra(MINUTE, time.second)
}
val pendingIntent = PendingIntent.getBroadcast(
context,
NOTIFICATION_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
val alarmClockInfo = AlarmManager.AlarmClockInfo(
dueTime.timeInMillis,
pendingIntent
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (alarmManager.canScheduleExactAlarms()) {
registerAlarm(pendingIntent, alarmClockInfo)
}
}
else registerAlarm(pendingIntent, alarmClockInfo)
}
private fun registerAlarm(intent: PendingIntent, alarmClockInfo: AlarmClockInfo) {
alarmManager.setAlarmClock(
alarmClockInfo,
intent
)
/*alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
dueTime.timeInMillis,
pendingIntent
)*/
}
override fun cancel() {
alarmManager.cancel(
PendingIntent.getBroadcast(
context,
NOTIFICATION_REQUEST_CODE,
Intent(context, NotificationReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
override fun setNotificationSchedule(register: Boolean, time: Time) {
when {
register -> schedule(time)
else -> cancel()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment