Advertisement
ipdan4ik

[lb10] TimeService.kt

Apr 23rd, 2021
926
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.80 KB | None | 0 0
  1. package com.example.lb10
  2.  
  3. import android.app.Service
  4. import android.content.Intent
  5. import android.os.Binder
  6. import android.os.IBinder
  7. import android.util.Log
  8. import kotlinx.coroutines.GlobalScope
  9. import kotlinx.coroutines.Job
  10. import kotlinx.coroutines.delay
  11. import kotlinx.coroutines.launch
  12.  
  13. class TimeService : Service() {
  14.     private var counter = 0
  15.     private lateinit var job: Job
  16.     private val myBinder = MyBinder()
  17.     private var counterInterval: Long = 1000
  18.     private var startValue: Int = 0
  19.     override fun onBind(intent: Intent?): IBinder? {
  20.         return myBinder
  21.     }
  22.  
  23.     inner class MyBinder : Binder() {
  24.         fun getService() : TimeService {
  25.             return this@TimeService
  26.         }
  27.     }
  28.  
  29.     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
  30.         job = GlobalScope.launch {
  31.             counter = startValue
  32.             while (true) {
  33.                 delay(counterInterval)
  34.                 Log.d("SERVICE", "Timer Is Ticking: $counter (interval: $counterInterval)")
  35.                 val intent = Intent(BROADCAST_TIME_EVENT);
  36.                 intent.putExtra("counter", counter);
  37.                 sendBroadcast(intent);
  38.                 counter++
  39.             }
  40.         }
  41.         return super.onStartCommand(intent, flags, startId)
  42.     }
  43.  
  44.     override fun onDestroy() {
  45.         counter = 0
  46.         Log.d("SERVICE", "onDestroy")
  47.         job.cancel()
  48.         super.onDestroy()
  49.     }
  50.  
  51.     fun setCounter(a: Int) {
  52.         counter = a
  53.         startValue = a
  54.         Log.d("SERVICE", "setCounter to $a")
  55.     }
  56.  
  57.     fun resetCounter() {
  58.         counter = startValue
  59.         Log.d("SERVICE", "resetCounter")
  60.     }
  61.  
  62.     fun setInterval(a: Long) {
  63.         counterInterval = a
  64.         Log.d("SERVICE", "setInterval to $a")
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement