6

Is it possible for a background thread to enqueue a message to the main UI thread's handler and block until that message has been serviced?

The context for this is that I would like my remote service to service each published operation off its main UI thread, instead of the threadpool thread from which it received the IPC request.

CJBS
  • 15,147
  • 6
  • 86
  • 135
zer0stimulus
  • 22,306
  • 30
  • 110
  • 141

1 Answers1

5

This should do what you need. It uses notify() and wait() with a known object to make this method synchronous in nature. Anything inside of run() will run on the UI thread and will return control to doSomething() once finished. This will of course put the calling thread to sleep.

public void doSomething(MyObject thing) {
    String sync = "";
    class DoInBackground implements Runnable {
        MyObject thing;
        String sync;

        public DoInBackground(MyObject thing, String sync) {
            this.thing = thing;
            this.sync = sync;
        }

        @Override
        public void run() {
            synchronized (sync) {
                methodToDoSomething(thing); //does in background
                sync.notify();  // alerts previous thread to wake
            }
        }
    }

    DoInBackground down = new DoInBackground(thing, sync);
    synchronized (sync) {
        try {
            Activity activity = getFromSomewhere();
            activity.runOnUiThread(down);
            sync.wait();  //Blocks until task is completed
        } catch (InterruptedException e) {
            Log.e("PlaylistControl", "Error in up vote", e);
        }
    }
}
Ryan
  • 3,579
  • 9
  • 47
  • 59