János János - 1 year ago 169
Java Question

How to access main thread from worker thread in Java?

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

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

Answer Source

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() {
      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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download