Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TimerService : Service(), KoinComponent {
- companion object {
- const val TIMER_VAL = "TIMER_VAL"
- }
- private val notifManager by inject<NotificationHandler>()
- private val repo by inject<TimerRepo>()
- private val timerState = repo.sharedTimerState
- .stateIn(
- serviceScope,
- SharingStarted.WhileSubscribed(5000L),
- TimerGlobalState()
- )
- private val tag = "TimerService"
- private var notifId by mutableIntStateOf(0)
- private lateinit var notif: NotificationCompat.Builder
- override fun onBind(p0: Intent?): IBinder? = null
- override fun onCreate() {
- super.onCreate()
- notif =
- NotificationCompat
- .Builder(this, Consts.TIMER_CHANNEL)
- .setSmallIcon(R.mipmap.ic_launcher_foreground)
- .setPriority(NotificationManager.IMPORTANCE_HIGH)
- .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
- .setContentTitle("KModoro - Timer")
- .setOngoing(true)
- .setAllowSystemGeneratedContextualActions(false)
- .setOnlyAlertOnce(true)
- .setContentIntent(
- PendingIntent.getActivity(
- this,
- 0,
- Intent(
- this,
- MainActivity::class.java
- ),
- PendingIntent.FLAG_MUTABLE,
- ),
- )
- }
- override fun onStartCommand(
- intent: Intent?,
- flags: Int,
- startId: Int,
- ): Int {
- super.onStartCommand(intent, flags, startId)
- when (intent?.action) {
- TimerActions.START.name -> {
- val currentValue =
- intent.getLongExtra(TIMER_VAL, 0L)
- KLogger.d("onStartCommand: $currentValue", tag = tag)
- startTimer(currentValue)
- }
- TimerActions.CLEAR.name -> clearTimer()
- TimerActions.PAUSE.name -> pauseTimer()
- TimerActions.ADD_MINUTE.name -> addOneMinute()
- TimerActions.REPLAY.name -> replayTimer()
- }
- return START_STICKY
- }
- private fun addOneMinute() {
- }
- private fun replayTimer() {
- }
- private fun startTimer(value: Long) {
- val notification = notif.setContentText(value.formatTime()).build()
- serviceScope.launch {
- repo.activateTimer()
- repo.sharedTimerState.collect {
- updateNotification(it.time)
- }
- }
- startForeground(Consts.TIMER_NOTIFICATION_ID, notification)
- }
- private fun clearTimer() {
- repo.resetTimer()
- stopSelf()
- }
- private fun pauseTimer() {
- serviceScope.launch {
- repo.stopTimer(TimerState.Paused)
- }
- }
- private fun updateNotification(value: Long) {
- val notification =
- notif
- .setContentText(value.formatTime())
- .setContentIntent(
- PendingIntent.getActivity(
- this,
- 0,
- Intent(
- this, MainActivity::class.java
- ).also {
- it.putExtra("TARGET_SCREEN", Destination.TimerScreen::class.simpleName)
- },
- PendingIntent.FLAG_IMMUTABLE,
- ),
- ).build()
- notifId = notification.number
- notifManager.notify(Consts.TIMER_NOTIFICATION_ID, notification)
- }
- }
- enum class TimerActions {
- START,
- CLEAR,
- PAUSE,
- ADD_MINUTE,
- REPLAY,
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement