Android multithreading with event listeners
I am on my android app. I have a UI thread (obviously) as well as some other themes that I use to do some work. My UI thread has listeners waiting on other threads to complete (call this event workComplete
).
I ran into the problem right there. When my listener receives a call, the current thread is a worker thread, not a UI thread. So if I try to do something that needs to happen from the UI thread (change of view, etc.) It breaks or gives a warning.
My question is, what's the best approach to do this? I wanted to get back to the UI thread when the worker finished and called the listener event workComplete
.
Thank!
source to share
The approach to the commonly used UI thread is to publish the 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...
}
}
source to share
You can use the method runOnUiThread()
in the class Activity
.
From the documentation:
void android.app.Activity.runOnUiThread (Runnable action)
Launches the specified action on the UI thread. If the current thread is a UI thread, then the action is executed immediately. If the current thread is not a UI thread, the action is posted to the event queue of the UI thread.
Parameters: 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 are inside a fragment, you can call getActivity().runOnUiThread(runnable)
.
source to share
According to me, you should be using Thread pool Executor and even google has a sample code that will describe everything how an image is passed to multiple threads, how to submit a task on loading and decoding, and update the ui thread, this is the best example for me. to find out and it helps me a lot.
https://developer.android.com/training/multiple-threads/create-threadpool.html
Handler
https://developer.android.com/training/multiple-threads/communicate-ui.html
source to share