-
Notifications
You must be signed in to change notification settings - Fork 2
/
MainActivity.kt
126 lines (99 loc) · 3.04 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package code.with.cal.persistenttimerapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import code.with.cal.persistenttimerapp.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity()
{
lateinit var binding: ActivityMainBinding
lateinit var dataHelper: DataHelper
private val timer = Timer()
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
dataHelper = DataHelper(applicationContext)
binding.startButton.setOnClickListener{ startStopAction() }
binding.resetButton.setOnClickListener{ resetAction() }
if(dataHelper.timerCounting())
{
startTimer()
}
else
{
stopTimer()
if(dataHelper.startTime() != null && dataHelper.stopTime() != null)
{
val time = Date().time - calcRestartTime().time
binding.timeTV.text = timeStringFromLong(time)
}
}
timer.scheduleAtFixedRate(TimeTask(), 0, 500)
}
private inner class TimeTask: TimerTask()
{
override fun run()
{
if(dataHelper.timerCounting())
{
val time = Date().time - dataHelper.startTime()!!.time
binding.timeTV.text = timeStringFromLong(time)
}
}
}
private fun resetAction()
{
dataHelper.setStopTime(null)
dataHelper.setStartTime(null)
stopTimer()
binding.timeTV.text = timeStringFromLong(0)
}
private fun stopTimer()
{
dataHelper.setTimerCounting(false)
binding.startButton.text = getString(R.string.start)
}
private fun startTimer()
{
dataHelper.setTimerCounting(true)
binding.startButton.text = getString(R.string.stop)
}
private fun startStopAction()
{
if(dataHelper.timerCounting())
{
dataHelper.setStopTime(Date())
stopTimer()
}
else
{
if(dataHelper.stopTime() != null)
{
dataHelper.setStartTime(calcRestartTime())
dataHelper.setStopTime(null)
}
else
{
dataHelper.setStartTime(Date())
}
startTimer()
}
}
private fun calcRestartTime(): Date
{
val diff = dataHelper.startTime()!!.time - dataHelper.stopTime()!!.time
return Date(System.currentTimeMillis() + diff)
}
private fun timeStringFromLong(ms: Long): String
{
val seconds = (ms / 1000) % 60
val minutes = (ms / (1000 * 60) % 60)
val hours = (ms / (1000 * 60 * 60) % 24)
return makeTimeString(hours, minutes, seconds)
}
private fun makeTimeString(hours: Long, minutes: Long, seconds: Long): String
{
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
}