I created a Handler()
in my onCreate method of my MainActivity to run some code, so obviously everytime onCreate gets called, a new instance of my handler is created. When user navigates away from MainActivity and then comes back to it, a new handler is created.
handler.postDelayed(object : Runnable {
override fun run() {
try {
player.money += player.cps
player.moneyEarned += player.cps
updateText()
save()
} catch (e: Exception) {
println("ERROR")
}
handler.postDelayed(this, 1000)
}
}, 0)
How do I make it so that a new handler is not created when navigating back to my MainActivity? Or somehow get this handler to run at a global application level which means only one instance of it will ever be created?
Info: Creating too many of these handlers caused my app to lag, then crash. Too many read and write and calculation operations I guess. I discovered this after navigating away from MainActivity more than 50 times.