How to wait for webview.post to complete?

1.4k views Asked by At

In the below code, outside is printed before inside. I want the order to be inside first and then outside. So how do I ensure that the Runnable is finished before the second Log is reached?

webView.post(new Runnable() {
    @Override
    public void run() {
        Log.d("check", "inside");
    }
});

// some code needed here

Log.d("check", "outside");

Some code must be inserted where to comment is to achieve this.

EDIT: I am doing all the work in a background service.

[P.S.: Those who are curious as to why I am doing this, it is so because unless I add the webview.post, I keep getting the following error: "All WebView methods must be called on the same thread.". Anyway, this shouldn't affect you from answering the question.]

1

There are 1 answers

4
Alex Forcier On BEST ANSWER

You might try using a CountDownLatch:

final CountDownLatch latch = new CountDownLatch(1);

webView.post(new Runnable() {
    @Override
    public void run() {
        Log.d("check", "inside");
        latch.countDown();
    }
});

// some code needed here
latch.await();

Log.d("check", "outside");

However, you wouldn't want to use latch.await() on the UI thread, as that's a blocking method. If you wanted to run this on the UI thread it would be best to replace latch.countDown() with a call to a callback method, which would in turn run Log.d("check", "outside").