Communicating with the UI Thread

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

The UI Thread is the main thread of the application. All of your application components (Activities, Services, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.

The main responsible of UI thread is to create and update UI widgets, process user touch event. If we do long running task in UI thread, such as uploading/loading data to/from the cloud; saving/loading cached data to/from disk; sorting, filtering and searching data, that will cause UI response not smooth, in server cases, it will cause ANR, or NetworkOnMainThreadException.

That's means we need to offload long-running task to worker thread. However, if we update UI widgets directly in worker thread, it will cause CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

So the question becomes, how to update UI after data is ready? in other words, how to move data from a worker thread to the UI thread?

  • Use a Handler that's running on the UI thread.

    we can pass the UI handler through constructor of worker thread, or create UI handler in worker thread through getMainLooper directly. Then we can send the data through Message object, or post a Runnable object directly.

  • Define a callback with data as its parameter.

  • AsyncTask

  • Rx