mport android.content.Context
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
const val SHARE_DATA = "TIME_DATA"
const val TIME_KEY = "TIME"
const val TIMEOUT = 45*1000L // 45sec
class MainActivity : AppCompatActivity() {
var time = 0L
private lateinit var handler: Handler
private val runnable = Runnable { tictak() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
handler = Handler()
time = load()
if (timeLeftSec() > 0){
startTicTak()
}
button.setOnClickListener {
time = Date().time + TIMEOUT
save(time)
startTicTak()
}
}
private fun startTicTak() {
showTextView()
tictak()
}
private fun tictak() {
val timeLeft = timeLeftSec()
if (timeLeft > 0) {
textView.text = "Осталось $timeLeft"
handler.postDelayed(runnable, 1000L)
} else {
showButton()
}
}
private fun showTextView() {
button.visibility = View.GONE
textView.visibility = View.VISIBLE
}
private fun showButton() {
button.visibility = View.VISIBLE
textView.visibility = View.GONE
}
private fun timeLeftSec() = (time - Date().time) / 1000L
private fun save(time: Long) {
val preferences = getSharedPreferences(SHARE_DATA, Context.MODE_PRIVATE)
val editor = preferences.edit()
editor.putLong(TIME_KEY, time)
editor.apply()
}
private fun load(): Long {
val preferences = getSharedPreferences(SHARE_DATA, Context.MODE_PRIVATE)
return preferences.getLong(TIME_KEY, 0)
}
}