Reputation: 13537
This post Communicating between threads section says that
The issue is particularly acute if the task on the new thread wishes to modify views associated with main UI thread, because it is strictly forbidden to do so directly.
Why is it prohibited/forbidden.
Upvotes: 1
Views: 992
Reputation: 28470
The Handler helps queue requests from worker threads in a MessageQueue so they are executed sequentially on the main thread.
The following blog post is quite helpful to learn more about how Handlers work:
Android – Multithreading in a UI environment
Upvotes: 1
Reputation: 33534
Please read this,
Its always a good practice to keep the UI work on UI Thread, and Non-UI work on Non-UI Thread, and since HoneyComb its a law. We always start with the Dedicated UI Thread, but as soon as we create another thread to do some Non-UI task, we get dropped of the Dedicated UI Thread, and lands on a Non-UI thread, once when we finish our work and want to put the processed Output on the UI thread, its not possible directly, because we have lost the reference to the UI thread. Now Handler helps in getting the reference to the thread in which it was created. So its a good practice to initialize the Handler in onCreate(), and then later call this reference from within the non-ui thread.
Upvotes: 1
Reputation: 33534
Use AsyncTask<> provided by android, it synchronizes the UI and Non-UI threads
Methods in AsyncTask<>
doInBackground(String...) // Work on the Non-UI thread
postExecute(String result) // Getting the Output from the Non-Ui thread and
Putting the Output back on the UI Thread
Upvotes: 0