Running code in Main thread from another thread using Handler

runOnUiThread() will execute the Runnable immediately. but post() always puts the Runnable at the end of the event queue, even if you are already on the main application thread

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);
MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});

References
https://stackoverflow.com/questions/11123621/running-code-in-main-thread-from-another-thread
https://stackoverflow.com/questions/12850143/android-basics-running-code-in-the-ui-thread