Reputation: 892
I'm in my Android app I have the UI Thread (obviously) and also some other Threads I use to do some work. There are listeners in my UI thread waiting for the work to be completed in the other threads (let's call it workComplete
event).
I'm facing an issue right there. When my listener receives the call, the current thread is the worker thread, not the UI thread. So, if I try to do something that should come from the UI thread (modifying a view, etc.), it breaks or gives a warning.
My question is: what's the best approach for this? I wanted to be back in the UI thread when worker finished it's job and calls listener's workComplete
event.
Thanks!
Upvotes: 4
Views: 2783
Reputation: 1432
According to me you have to use Thread pool Executor and even google have sample code which will describe everything how image is submitted to multiple thread how to submit task when download and decode completed and update ui thread it's best example for me to learn and it help me a lot.
https://developer.android.com/training/multiple-threads/create-threadpool.html
handler
https://developer.android.com/training/multiple-threads/communicate-ui.html
Upvotes: -1
Reputation: 1620
You can use the runOnUiThread()
method in the Activity
class.
From the documentation:
void android.app.Activity.runOnUiThread(Runnable action)
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.
Parameters: action the action to run on the UI thread
So in your workComplete event:
runOnUiThread(new Runnable() {
public void run() {
// Do some cool UI stuff here ...
}
}
If you're inside a fragment you can call getActivity().runOnUiThread(runnable)
.
Upvotes: 3
Reputation: 11113
The approach to get back on the UI thread commonly used is to post using a Handler that was originally created on the UI thread:
//create thread on UI Thread (associates with Looper)
Handler handler = new Handler();
//then use it in a background thread
handler.post(new Runnable(){
public void run(){
//back on UI thread...
}
}
Upvotes: 2