2

Let's say that I have a mainActivity and a reference to it everywhere.

I switch activities later in the app and I'm not sure which is currently 'on the top' and if it's a mainActivity.

Is it wrong to call mainActivity.runOnUIThread() when there's another activity visible? Would it work without any errors in the future? Or should I call it only on the current activity?

Technically, there's one UI thread so...

1 Answers1

0

You described scenario is essentially on how to communicate with the UI Thread. It's incredibly bad practice to keep a reference on your mainActivity everywhere. It could be in a state where calls on the UI Thread are not allowed anymore etc.

But you can still achieve to run code in your UI Thread. Here is the android developer guide on Communication with the UI Thread and in short it's essentially this

new Handler(Looper.getMainLooper()).post(yourRunnableOnUi);
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • Yeah, I'm just looking for a 'static' way for posting these runnables. Do you know what are the disadventages of using your solution with handler? –  Jan 22 '17 at 13:05
  • @Spectre There is basically no disadvantage. It's the preferred way of the android os. You may want to have a closer control if you are doing `postDelayed` stuff on the handler. You might want to keep a reference to the handler and if you don't need it anymore you can call `removeMessagesAndCallbacks` on the `Handler` to release the resources it allocated. – Murat Karagöz Jan 22 '17 at 13:20