1

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?

lysergic-acid
  • 19,570
  • 21
  • 109
  • 218

1 Answers1

1

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?

Community
  • 1
  • 1
ToYonos
  • 16,469
  • 2
  • 54
  • 70
  • Thanks. My question specifically mentioned though that i don't want to execute on the UI thread, but on any arbitrary thread in the process. – lysergic-acid Nov 23 '14 at 20:21
  • Thanks. Does that have to be placed in a custom Thread class? the situation i have is a thread that was already created by the framework. Can i add a Handler and a Looper to that and expose the Handler to other threads to post to ? Also, what do you mean by all tasks should be done through the message queue ? – lysergic-acid Nov 24 '14 at 09:37
  • 1
    This question will help you understand : http://stackoverflow.com/questions/6984263/android-looper-and-call-stack A Looper, when it is looping, will block your thread, so this one will not be able to perfom any other operation. If this thread comes from a framework, it could be a problem. – ToYonos Nov 24 '14 at 09:45