sajjoo
sajjoo

Reputation: 6614

Call Main thread from secondary thread in Android

How to call Main thread from secondary thread in Android?

Upvotes: 44

Views: 36808

Answers (5)

Ravindra babu
Ravindra babu

Reputation: 38910

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.

Upvotes: 1

Tad
Tad

Reputation: 4784

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.

Upvotes: 1

thoredge
thoredge

Reputation: 12601

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

activity.runOnUiThread(new Runnable() {
    public void run() {
        ... do your GUI stuff
    }
});

Upvotes: 89

Ben Weiss
Ben Weiss

Reputation: 17922

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

Upvotes: 2

Jesus Oliva
Jesus Oliva

Reputation: 2302

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
        [ . . . ]
    }
}

Upvotes: 24

Related Questions