title: Android - Wait for a UI thread callback without returning from function
body: <p>I'm investigating making a framework to use a WebView to run arbitrary JavaScript.  It works fine. </p>
  
  <p>For programmer convenience I'd like to be able to make a synchronous call invoking a bit of JavaScript, and get the result within a single function (No comments please about code execution speed.  Of course it'll be slow).</p>
  
  <p>But the threading model is causing me problems. WebView makes its callbacks to the UI thread - which is nice and programmer-friendly.  But it makes trouble for me.  I'd like to be able to do this in the UI thread:</p>
  
  <pre><code>String four = X.invokeJavaScriptReturningString("2+2"); // result "4"
  </code></pre>
  
  <p>where the method is as follows:</p>
  
  <pre><code>public String invokeJavaScriptReturningString( final String javaScript) throws InterruptedException {
      final CountDownLatch latch = new CountDownLatch(1);
      final String[] result = new String[1]; // Kludge - array is assignable from nested class.
  
      ValueCallback&lt;String&gt; callback = new ValueCallback&lt;String&gt;() {
          @Override
          public void onReceiveValue(String s) {
              result[0] = s;
              latch.countDown();
          }
      };
      mWebView.evaluateJavascript(javaScript, callback);
  
      latch.await(99, TimeUnit.SECONDS);
      return result[0];  
  }
  </code></pre>
  
  <p>But of course the callback message gets queued in the UI thread message queue, and the function blocks for 99 seconds then returns null.</p>
  
  <p>Some message-based thread models have a way to work around this; something like:</p>
  
  <pre><code>while (!latch.await(1, TimeUnit.MILLISECONDS) {
      // Process any messages in the UI thread Looper queue.
  }
  </code></pre>
  
  <p>But I can't find any way to get at the Android Looper queue.  </p>
  
  <p>Any suggestions how to solve this?</p>