简体   繁体   中英

Android multithreading with event listeners

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!

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...
    }
}

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) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM