Search code examples
javaandroidmultithreadingandroid-asynctasklooper

How to post callbacks in Android to any arbitrary thread


I am using the Unity game engine which also supports exporting to Android.

The engine uses multiple threads, including the UI thread and a separate scripting thread where all the user custom code is executing.

My scenario requires that i call some operation in a background thread, and i would like to marshal the result back to the main scripting thread.

I know the basics of the AsyncTask, Executor and Looper classes. Out of these, Looper seems like a good candidate since it allows setting up a queue and post back messages to a given thread (AsyncTask is "hardwired" to run the callback on the UI thread, which is not what i want here).

What is the proper way of achieving this?


Solution

  • There is 3 main ways to communicate with the UI thread :

    1. Activity.runOnUiThread(Runnable)

    2. View.post(Runnable)

    3. Handlers

    In your case, I advice you to create an Handler, as the 2 first solutions imply that you have a reference on your Activity or a View

    Edit

    If you want to use any thread in your app, just make sure a Looper has been set, and use an associated Handler

    class YourLooperThread extends Thread
    {
        // make it accessible from the outside
        private Handler handler;
    
        @Override public void run()
        {
            Looper.prepare();
    
            // Customize your handler, it has to be used in any thread which want to push a message in this thread's looper message Queue
            handler = new Handler();
    
            Looper.loop();
        }
    }
    

    Be careful : all the other tasks you want to do in that thread must be done through the message queue, i.e posting a runnable in the handler. More information here : Handlers, MessageQueue, Looper, do they all run on the UI thread?