2

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.

Tad
  • 889
  • 9
  • 23
  • Each thread can have its own `Handler` . So when you call it from Ui thread you will get a `Handler` with `MainLooper` which is equivalent to `new Handler(getMainLooper())` . So for using in same thread for exa in `MainThread` you can create a `MainThreadHandler` Utility class. – ADM Apr 30 '18 at 11:46
  • I don't even know which thread my handler is running on, I'm guessing it is already on main thread since I did not create a thread. – Tad Apr 30 '18 at 11:49
  • 1
    You can use a singleton approach: https://stackoverflow.com/questions/40398072/singleton-with-parameter-in-kotlin – leonardkraemer Apr 30 '18 at 11:51
  • Default constructor associates this handler with the Looper for the current thread. So in your case it must be main Thread. – ADM Apr 30 '18 at 11:56
  • You can create a `Handler` in application class and access it throughout the app . – ADM Apr 30 '18 at 12:02
  • @ADM An application can be considered as a singleton? – Farhana Naaz Ansari Apr 30 '18 at 12:20
  • Yeah In a way . Read https://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android. – ADM Apr 30 '18 at 12:27
  • Are you using weak reference for the activity inside the handler? If not could it be a garbage collection issue? – Kalyan Raghu Apr 30 '18 at 14:15

1 Answers1

0

You can extend your Application class, so you will have only one holder, you can also make it static.

In order to extend Application: 1. Create App class public class App extends Application 2. In your manifest under application tag set name=".App"

There is onCreate method which can be used for that purpose

Maksym V.
  • 2,877
  • 17
  • 27
  • The thing you said to do to the manifest does not work. name=".App" goes up in error. – Tad Oct 31 '18 at 18:03