0

While it is useful to run long standing tasks on their own thread running code in the UIThread is necessary in order to update the UI components. Otherwise your application will throw the CalledFromWrongThreadException during execution. How can you run code on the UIThread?

Luke Allison
  • 3,118
  • 3
  • 24
  • 40
  • possible duplicate of [android - calling ui thread from worker thread](http://stackoverflow.com/questions/13746940/android-calling-ui-thread-from-worker-thread) – durron597 Aug 04 '15 at 04:04

2 Answers2

1

There are a number of ways this can be achieved:

  1. Use runOnUiThread() method call
  2. Use post() method call
  3. Use the Handler framework
  4. Use a Broadcasts and BroadcastReceiver (optionally with LocalBroadcastManager)
  5. Use an AsyncTask's onProgressUpdate() method

Method 1:

    runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // do something
                }
            });

Read more: http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/#ixzz3hnx3hdS5

Luke Allison
  • 3,118
  • 3
  • 24
  • 40
1

Yes you can use handler to communicate between Worker Thread and UI Thread, put below code snippet into worker thread from which you want to update your UI,

Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("file", pdfPath);
message.setData(bundle);
handler.sendMessage(message); // pass handler object from activity

put Handler related code into Activity class

Handler handler = new android.os.Handler() {
    @Override
    public void handleMessage(Message msg) {
          String filePath = msg.getData().getString("file"); // You can change this according to your requirement.

    }
};

If you aren't familiar with Handler mechanism then first read following link, it will help you

https://developer.android.com/training/multiple-threads/communicate-ui.html

Umang Kothari
  • 3,674
  • 27
  • 36