43

How to call Main thread from secondary thread in Android?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
sajjoo
  • 6,576
  • 20
  • 65
  • 86

5 Answers5

88

The simplest way is to call runOnUiThread(...) from your thread

activity.runOnUiThread(new Runnable() {
    public void run() {
        ... do your GUI stuff
    }
});
thoredge
  • 12,237
  • 1
  • 40
  • 55
24

My recommendation to communicate threads in the same process is sending messages between those threads. It is very easy to manage this situation using Handlers:

http://developer.android.com/reference/android/os/Handler.html

Example of use, from Android documentation, to handling expensive work out of the ui thread:

public class MyActivity extends Activity {

    [ . . . ]
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        [ . . . ]
    }

    protected void startLongRunningOperation() {

        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
                mResults = doSomethingExpensive();
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }

    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on the data in mResults
        [ . . . ]
    }
}
Jesus Oliva
  • 2,282
  • 14
  • 18
2

You'll need a Handler that passes the information back to the main thread.

Ben Weiss
  • 17,182
  • 6
  • 67
  • 87
1

Also, it's good to remember that if you get your secondary thread through an AsyncTask, you have the option to call onProgressUpdate(), onPostExecute(), etc., to do work on the main thread.

Tad
  • 4,668
  • 34
  • 35
1

Sample code using HandlerThread

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Handler responseHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Result from UIHandlerThread:"+(int)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };

        HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
            public void run(){
                /* Add your business logic to pupulate attributes in Message
                   in place of sending Integer 5 as in example code */
                Integer a = 5;
                Message msg = new Message();
                msg.obj = a;
                responseHandler.sendMessage(msg);
                System.out.println(a);
            }
        };
        handlerThread.start();

    }

}

Explanation:

  1. In above example, HandlerThread post a Message on Handler of UI Thread, which has been initialized with Looper of UI Thread.

    final Handler responseHandler = new Handler(Looper.getMainLooper())
    
  2. responseHandler.sendMessage(msg); sends Message from HandlerThread to UI Thread Handler.

  3. handleMessage processes Message received on MessageQueue and shows a Toast on UI Thread.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211