-2

Read many overkilled, overcomplicated solution here in SO, for such an easy question, how to access main thread from a worker thread, to execute some code on it.

In iOS dispatch_get_main_queue() method returns main thread. How in Java?

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0UL), ^{
    //do background thread stuff

    dispatch_async(dispatch_get_main_queue(), ^{
        //update UI
    });
});
Community
  • 1
  • 1
János
  • 32,867
  • 38
  • 193
  • 353
  • 3
    Possible duplicate of [Running code in main thread from another thread](http://stackoverflow.com/questions/11123621/running-code-in-main-thread-from-another-thread) – Augusto Sep 16 '16 at 22:24
  • 2
    Neither of the links in your question have anything to do with Android. – CommonsWare Sep 16 '16 at 22:33

2 Answers2

1

In Android you can't access the main thread (UI Thread) directly, but you can queue jobs on it, so you need to create a Handler and using that handler to post jobs (Runnable) on main thread.

Below is an example of how you can post on UI Thread using Handler

new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
      @Override
      public void run() {
        //Doing job here
      }
    })

and also as @CommonsWare mentioned in the comments, there is another ways to access UI thread:

  • if you have instance of any View you can use View.post(Runnable)
  • if you have instance of Activity, you can use Activity.runOnUiThread(Runnable)

Btw accessing main thread in Android is totally different than Java Desktop Apps

Community
  • 1
  • 1
Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
-1

Running your code on main thread from another:

runOnUiThread(new Runnable() {
        @Override
        public void run() {
           // Your code here
        }
});

Hope this helps

Lucas Moretto
  • 404
  • 1
  • 6
  • 18
  • Curious why the downvote? Explanation? This code works fine to change state of the UI in the `doInBackground()` method of an AsyncTask for example. Is this not the "proper" way? – ShadowGod Sep 16 '16 at 23:09