什么时候调用WebViewClient方法?

时间:2012-11-12 18:14:34

标签: android webview webviewclient

我在我的应用中有一个webview,首先加载a.html,点击a.html内的按钮,然后b.html将被加载,点击b.html内的按钮,然后将启动一个活动。简而言之,订单是 a.html-> b.html->启动活动。我的webView扩展了WebViewClient,并覆盖其方法如下。

private class WebViewHandler extends WebViewClient
    {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) 
        {
            Log.d("onPageStarted", "onPageStarted:" + url );
            mProgress.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) 
        {
            Log.d("onPageFinished", "onPageFinished:" + url );
            mProgress.setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) 
        {
            Log.d("url", "onPageoverloaded the url: "+url);
            String tutorialId = url.substring(url.lastIndexOf("=") + 1);
            MetaioDebug.log("Tutorial Id detected: "+tutorialId);
            if (url.startsWith("metaio://"))
            {
                if (tutorialId != null)
                {
                    MetaioDebug.log("Native code tutorial to be loaded #"+tutorialId);
                    if (tutorialId.equals("1"))
                    {
                        Intent intent = new Intent(getApplicationContext(), Tutorial1.class);
                        startActivity(intent);
                    }

                return true;
            }
    }

问题是onPageStarted()仅在a.html开始加载时调用,但在b.html开始加载时不会被调用。仅当我点击b.html中的按钮而不是a.html中的按钮时才会调用shouldOverrideUrlLoading(WebView view, String url)

我很困惑这三种方法何时被调用?

1 个答案:

答案 0 :(得分:0)

我认为onPageFinished()应该返回false

来自documentation for shouldOverrideUrlLoading ()

If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url.

不知道为什么它在a.html上不起作用,但它可能与您的返回值有关,因为系统将在某个时候确定它是否会处理自身向前发展的事情。

关于您的onPageStarted问题,我认为您看到了预期的行为。 Documentation for onPageStarted():

Notify the host application that a page has started loading. This method is called once for each main frame load so a page with iframes or framesets will call onPageStarted one time for the main frame. This also means that onPageStarted will not be called when the contents of an embedded frame changes, i.e. clicking a link whose target is an iframe.

我认为您的WebView认为自己处于“已完成”状态,因为它已经完成了您已经要求它从a.html执行的原始渲染。

解决方法是使用b.html创建和扩充新的WebView,以保证调用onPageFinished()。我认为这取决于你如何将b.html加载到webview中。

您是否暗示在加载onPageFinished()之后看到b.html被叫,而不是onPageStarted()?或者两者都没有被召唤?

根据评论添加:

尝试以另一种方式加载b.html,以便WebView了解它正在加载一个全新的资源:

让当前值为href的{​​{1}}导致JavaScript方法回调到在Java中调用此类内容的JavaScript接口对象:

b.html

我认为这会让您的WebView认为它正在加载新资源,因此请同时调用webview.loadURL("file:///b.html"); //or whatever the file location of b.html is.onPageStarted()