Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.lb10
- import android.app.Service
- import android.content.Intent
- import android.os.Binder
- import android.os.IBinder
- import android.util.Log
- import kotlinx.coroutines.GlobalScope
- import kotlinx.coroutines.Job
- import kotlinx.coroutines.delay
- import kotlinx.coroutines.launch
- class TimeService : Service() {
- private var counter = 0
- private lateinit var job: Job
- private val myBinder = MyBinder()
- private var counterInterval: Long = 1000
- private var startValue: Int = 0
- override fun onBind(intent: Intent?): IBinder? {
- return myBinder
- }
- inner class MyBinder : Binder() {
- fun getService() : TimeService {
- return this@TimeService
- }
- }
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
- job = GlobalScope.launch {
- counter = startValue
- while (true) {
- delay(counterInterval)
- Log.d("SERVICE", "Timer Is Ticking: $counter (interval: $counterInterval)")
- val intent = Intent(BROADCAST_TIME_EVENT);
- intent.putExtra("counter", counter);
- sendBroadcast(intent);
- counter++
- }
- }
- return super.onStartCommand(intent, flags, startId)
- }
- override fun onDestroy() {
- counter = 0
- Log.d("SERVICE", "onDestroy")
- job.cancel()
- super.onDestroy()
- }
- fun setCounter(a: Int) {
- counter = a
- startValue = a
- Log.d("SERVICE", "setCounter to $a")
- }
- fun resetCounter() {
- counter = startValue
- Log.d("SERVICE", "resetCounter")
- }
- fun setInterval(a: Long) {
- counterInterval = a
- Log.d("SERVICE", "setInterval to $a")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement