/** * Posts the specified command to be executed on the main thread, waits for the request to * complete, and returns the result. * * @see sendRequestAsync */ private Object sendRequest(int command, Object argument) { if (Looper.myLooper() == mMainThreadHandler.getLooper()) { throw new RuntimeException("This method will deadlock if called from the main thread."); } MainThreadRequest request = new MainThreadRequest(argument); Message msg = mMainThreadHandler.obtainMessage(command, request); msg.sendToTarget(); // Wait for the request to complete synchronized (request) { while (request.result == null) { try { request.wait(); } catch (InterruptedException e) { // Do nothing, go back and wait until the request is complete } } } return request.result; }
/** * Asynchronous ("fire and forget") version of sendRequest(): Posts the specified command to be * executed on the main thread, and returns immediately. * * @see sendRequest */ private void sendRequestAsync(int command) { mMainThreadHandler.sendEmptyMessage(command); }