0

I've got a separate thread that handles some information and needs to let the user know of an error if something comes up during its execution, so right now I'm calling runOnUIThread() in order to create a Dialog and let the user know. My question is when exactly would that happen? Do the instructions in runOnUIThread() happen as soon as it's called, or does it wait for the UI thread to finish what it's currently doing first?

I'm asking because I'll be using graphics and in order to update the screen regularly the UI thread will be taken up by a loop to update and redraw the screen as far as I know.

Sizdian
  • 79
  • 1
  • 2
  • 9

1 Answers1

7

Do the instructions in runOnUIThread() happen as soon as it's called

No.

or does it wait for the UI thread to finish what it's currently doing first?

To some extent, not even that. The main application thread (a.k.a., UI thread) has a work queue. runOnUiThread() posts your Runnable to that queue. When the Runnable reaches the head of the queue, it is run. So, when the Runnable runs depends upon the size of that queue.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • @DalvikVM: Well, the thread exists, so long as the process is around, if that is what you mean. – CommonsWare Oct 13 '15 at 15:07
  • 1
    Does the app crash if you call runOnUITread() while the UI is not visible anymore? – Roel Oct 14 '15 at 07:45
  • @DalvikVM: `runOnUiThread()` is a method on `Activity`. If the activity is not destroyed, `runOnUiThread()` should be safe. If the activity is destroyed, you should have no need to call `runOnUiThread()`. – CommonsWare Oct 14 '15 at 11:11
  • Most of the times you call runOnUiThread() when you are in another thread. (because otherwise: what is the use?) So you don't know if the Activity is allready killed when you call this method. How to check this? Or do you just catch all exceptions (normally a bad practice)? – Roel Oct 14 '15 at 12:13
  • 1
    @DalvikVM: Call `isDestroyed()` on the activity. – CommonsWare Oct 14 '15 at 12:14
  • @DalvikVM: Then track your own `boolean isDestroyed`, set to `false` initially and set to `true` in your `onDestroy()` implementation. – CommonsWare Oct 14 '15 at 12:36