Home » Java » Android WebView onPageFinished synchronisation

Android WebView onPageFinished synchronisation

Posted by: admin July 12, 2018 Leave a comment

Questions:

I’m work on project, where i need to got and return some information of web page in android project (for example: rendered page height)
I’m using setWebViewClient with onPageFinished override method, but i can’t synchronise results from this method with returned value of my method (code of last try below)
I want to see something like this: (in people language)
1. Load data to webView
2. Program wait while data has loaded
3. Returning page height

How i can get results from onPageFinished method in main thread before return?
Thanks a lot for all replies!

P.S.

I’m tryed a lot of variants, but can’t do this 🙁
CustomWebView it’s my own class extended WebView that just initiate web view with parameters, that i needed

public int getWebPageHeight(Context context, final String data, final String encoding) {
    final CustomWebView webView = new CustomWebView(context);
    final CountDownLatch loadingLatch = new CountDownLatch (1);
    final MutableObject<Integer> measuredPageHeight = new MutableObject<>(0);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            measuredPageHeight.setValue(((CustomWebView)view).getVerticalScrollRange());
            loadingLatch.countDown();
        }
    });
    webView.loadData(data, "text/html;", encoding);

    try {
        loadingLatch.await(5L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return measuredPageHeight.getValue();
}

CustomWebView class:

public class CustomWebView extends WebView {

public CustomWebView(Context context) {
    this(context, 0, 0);
}

public CustomWebView(Context context, int width, int height) {
    super(context);

    setPadding(25, 25, 25, 25);
    layout(0, 0, width, height);
    setInitialScale(1);
    setWebChromeClient(new WebChromeClient());

    getSettings().setAppCacheEnabled(false);
    getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    getSettings().setAllowFileAccess(true);
    getSettings().setLoadWithOverviewMode(true);
    getSettings().setUseWideViewPort(true);
    getSettings().setJavaScriptEnabled(true);
    getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    getSettings().setPluginState(WebSettings.PluginState.ON);
    getSettings().setBuiltInZoomControls(true);
    getSettings().setSupportZoom(true);
    getSettings().setDisplayZoomControls(false);

    setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

public int getVerticalScrollRange() {
    return computeVerticalScrollRange();
}

public int getHorizontalScrollRange() {
    return computeHorizontalScrollRange();
}}
Answers: