Use of Android WebView (super detailed usage)

Android WebView is a special view on the Android platform. It can be used to display web pages. This WebView class can be used to display only one online web page in the app. Of course, it can also be used to develop browsers.

The internal implementation of WebView uses the rendering engine (WebKit) to display the content of the view, and provides the functions of web page forward and backward, web page zoom in, zoom out, search and so on.

WebView is a control that displays web pages based on WebKit engine. Android WebView adopts different WebKit version kernels in low and high versions.

The simplest way to use WebView is to directly display web page content. There are two steps:

Let's directly explain the case of using WebView control to display the web content of Baidu home page:

First, we add a WebView control to the layout file, as follows:

<WebView
         android:id="@+id/wv_webview"
         android:layout_width="match_parent"
         android:layout_height="match_parent" />

Next, we need to make the WebView control load and display the web page in the code, as follows:

public class WebViewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        //获得控件
        WebView webView = (WebView) findViewById(R.id.wv_webview);
        //访问网页
        webView.loadUrl("http://www.baidu.com");
        //系统认会通过手机浏览器打开网页,为了能够直接通过WebView显示网页,则必须设置
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                //使用WebView加载显示url
                view.loadUrl(url);
                //返回true
                return true;
            }
        });
    }
}

Of course, here, we need to load the data content on the network, so we also need to add network permissions:

<!-- 添加网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />

The operation display is as follows:

Generally speaking, WebView can be used not only alone, but also in combination with its subclasses. Let's also briefly understand:

//激活WebView为活跃状态,能正常执行网页的响应

webView.onResume() ;

 

//当页面被失去焦点被切换到后台不可见状态,需要执行onPause()

//通过onPause()动作通知内核暂停所有的动作,比如DOM的解析、JavaScript执行等

webView.onPause();

 

//当应用程序(存在webview)被切换到后台时,这个方法不仅仅针对当前的webview而是全局的全应用程序的webview

 //它会暂停所有webview的布局显示、解析、延时,从而降低cpu功耗

webView.pauseTimers()

//恢复pauseTimers状态

webView.resumeTimers();

 

//销毁Webview //在关闭了Activity时,如果Webview的音乐或视频,还在播放,就必须销毁Webview。

//但是注意:webview调用destory时,webview仍绑定在Activity上

//这是由于自定义webview构建时传入了该Activity的context对象

//因此需要先从父容器中移除webview,然后再销毁webview

rootLayout.removeView(webView);

webView.destroy();

//是否可以后退

Webview.canGoBack()

 

//后退网页

Webview.goBack()

 

//是否可以前进

Webview.canGoForward()

 

//前进网页

Webview.goForward()

 

//以当前的index为起始点前进或者后退到历史记录中指定的steps

//如果steps为负数则为后退,正数则为前进

Webview.goBackOrForward(intsteps)

Common usage: back key controls the back of web page

Problem: if you click the "back" button when browsing a web page without any processing, the entire browser using WebView will directly call finish() to end itself, close the current activity and return to the home screen (i.e. directly out of the browser);

Well, here, we can do some processing. After clicking the "back" key, let the web page return to the previous page instead of directly exiting the browser.

At this point, we can process the back event in the current activity, as follows:

public boolean onKeyDown(int keyCode,KeyEvent event) {
    if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
         mWebView.goBack();

         return true;

    }

    return super.onKeyDown(keyCode,event);

}

//清除网页访问留下的缓存

//由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.

Webview.clearCache(true);

 

//清除当前webview访问的历史记录

//只会webview访问历史记录里的所有记录除了当前访问记录

Webview.clearHistory();

 

//这个api仅仅清除自动完成填充的表单数据,并不会清除WebView存储到本地的数据

Webview.clearFormData();

There are three common subclasses of WebView: websettings class, webviewclient class and webchromeclient class.

Function: configure and manage WebView;

Configuration steps;

Common methods.

Configuration steps:

Step 1: add access to the network (androidmanifest. XML)

<uses-permission android:name="android.permission.INTERNET"/>

Step 2: generate a WebView component (there are two ways)

//方式1:直接在在Activity中生成

WebView webView = new WebView(this);

 

//方法2:在Activity的layout文件添加webview控件

WebView webview = (WebView) findViewById(R.id.webView);

Step 3: configure - use the websettings subclass (common method)

//声明WebSettings子类

WebSettings webSettings = webView.getSettings();

 

//如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript

webSettings.setJavaScriptEnabled(true);

 

//支持插件

webSettings.setPluginsEnabled(true);

 

 //设置自适应屏幕,两者合用

webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小

webSettings.setLoadWithOverviewmode(true); // 缩放至屏幕的大小

 

//缩放操作

webSettings.setSupportZoom(true); //支持缩放,认为true。是下面那个的前提。

webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放

webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

 

//其他细节操作

webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存

webSettings.setAllowFileAccess(true); //设置可以访问文件

webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口

webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片

webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

Common method: set WebView cache

//优先使用缓存

WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

//缓存模式如下:

    //LOAD_CACHE_ONLY: 不使用网络,只读取本地缓存数据

    //LOAD_DEFAULT: (认)根据cache-control决定是否从网络上取数据。

    //LOAD_NO_CACHE: 不使用缓存,只从网络获取数据.

    //LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据

 

//不使用缓存

WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

Invalid Sign

Common methods

Common methods:

shouldOverrideUrlLoading()

Function: when opening a web page, you do not call the system browser to open it, but directly display it in this WebView.

//Webview控件

Webview webview = (WebView) findViewById(R.id.webView);

//加载一个网页

webView.loadUrl("http://www.google.com/");

//重写shouldOverrideUrlLoading()方法,使得打开网页时不调用系统浏览器, 而是在本WebView中显示

webView.setWebViewClient(new WebViewClient(){
     @Override

     public boolean shouldOverrideUrlLoading(WebView view,String url) {
           view.loadUrl(url);

           return true;

      }

});

onPageStarted()

Function: call this method when loading the page. Here we can set a loading page to tell the user that the program is waiting for the network response.

webView.setWebViewClient(new WebViewClient(){
     @Override

      public void onPageStarted(WebView view,String url,Bitmap favicon) {
           //设定加载开始的操作

     }

});

onPageFinished()

Function: called at the end of page loading. We can close the loading bar and switch program actions.

webView.setWebViewClient(new WebViewClient(){
     @Override

     public void onPageFinished(WebView view,String url) {
           //设定加载结束的操作

     }

});

onLoadResource()

Function: it will be called when loading page resources, and each resource (such as pictures) will be called once.

webView.setWebViewClient(new WebViewClient(){
     @Override

     public boolean onLoadResource(WebView view,String url) {
           //设定加载资源的操作

     }

 });

onReceivedError()

Function: called when the server loading the page has an error (such as 404).

When an error such as 404 is encountered when using the WebView control in the app, if the error prompt page in the browser is also displayed, it will appear ugly. At this time, our app needs to load a local error prompt page, that is, how does WebView load a local page

//步骤1:写一个html文件(error_handle.html),用于出错时展示给用户看的提示页面

//步骤2:将该html文件放置到代码根目录的assets文件夹下

//步骤3:复写WebViewClient的onRecievedError方法 //该方法传回了错误码,根据错误类型可以进行不同的错误分类处理

webView.setWebViewClient(new WebViewClient(){
     @Override

     public void onReceivedError(WebView view,int errorCode,String description,String failingUrl){
           switch(errorCode) {
               case HttpStatus.SC_NOT_FOUND:

                    view.loadUrl("file:///android_assets/error_handle.html");

                    break;

           }

     }

});

onReceivedSslError()

Role: Processing HTTPS requests

WebView does not process HTTPS requests by default, and the page is blank

webView.setWebViewClient(new WebViewClient() {
     @Override

     public void onReceivedSslError(WebView view,SslErrorHandler handler,SslError error) {
          handler.proceed(); //表示等待证书响应

          // handler.cancel(); //表示挂起连接,为认方式

          // handler.handleMessage(null); //可做其他处理

      }

});

Role: assist WebView in handling JavaScript dialog boxes, website icons, website titles, etc.

Common methods

Common methods:

onProgressChanged()

Function: get the loading progress of the web page and display it

webview.setWebChromeClient(new WebChromeClient(){
     @Override

     public void onProgressChanged(WebView view,int newProgress) {
          if (newProgress < 100) {
                String progress = newProgress + "%";

                progress.setText(progress);

          } else {
                progress.setText(“100%”);

           }

});

Onreceivedtitle() function: get the title in the web page

Each web page has a title. For example, the title of www.baidu.com is "Baidu, you will know". So how do you know the title of the page being loaded by the current WebView and set it?

webview.setWebChromeClient(new WebChromeClient(){
     @Override

      public void onReceivedTitle(WebView view,String title) {
      titleview.setText(title);

 }

Note: how to avoid WebView memory leakage?

It is recommended not to define the WebView control in getapplicationgcontext () in the XML layout file, but directly create it in the activity when necessary, and the context object is recommended

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);

webView = new WebView(getApplicationContext());

webView.setLayoutParams(params);

mLayout.addView(webView);

When the activity destroys (WebView), first let the WebView load null content, then remove the WebView, then destroy the WebView, and finally set the WebView to null.

@Override

protected void onDestroy() {
    if (webView != null) {
        webView.loadDataWithBaseURL(null,"","text/html","utf-8",null);

        webView.clearHistory(); ((ViewGroup)

        webView.getParent()).removeView(mWebView);

        webView.destroy();

        webView = null;

    }

    super.onDestroy();

}

example:

Objective: to display "www.baidu. Com" and get the title, start loading prompt, loading progress and end loading prompt.

Concrete implementation

The operation display is as follows:

Step 1: add network permissions in the androidmanifest.xml manifest file

<uses-permission android:name="android.permission.INTERNET"/>

Step 2: layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取标题" />
    <TextView
        android:id="@+id/tv_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:text="开始加载提示" />
    <TextView
        android:id="@+id/tv_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取加载进度" />
    <TextView
        android:id="@+id/tv_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:text="结束加载提示" />
    <WebView
        android:id="@+id/wv_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Step 3: call and use the corresponding subclasses and methods according to the functions to be implemented

public class WebViewActivity extends AppCompatActivity {
    private WebView webView;
    private TextView tvTitle;
    private TextView tvStart;
    private TextView tvProgress;
    private TextView tvEnd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        //获得控件
        webView = (WebView) findViewById(R.id.wv_webview);

        //获得其他控件
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvStart = (TextView) findViewById(R.id.tv_start);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        tvEnd = (TextView) findViewById(R.id.tv_end);

        //访问网页
        webView.loadUrl("http://www.baidu.com");
        //系统认会通过手机浏览器打开网页,为了能够直接通过WebView显示网页,则必须设置
        //设置WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                //使用WebView加载显示url
                view.loadUrl(url);
                //返回true
                return true;
            }
            //加载前
            @Override
            public void onPageStarted(WebView view,Bitmap favicon) {
                tvStart.setText("开始加载!!");
            }
            //加载完成
            @Override
            public void onPageFinished(WebView view,String url) {
                tvEnd.setText("加载完成...");
            }
        });
        //设置WebChromeClient类
        webView.setWebChromeClient(new WebChromeClient() {
            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view,String title) {
                tvTitle.setText(title);
            }
            //进度显示
            @Override
            public void onProgressChanged(WebView view,int newProgress) {
                if (newProgress < 100) {
                    tvProgress.setText(newProgress + "%");
                } else {
                    tvProgress.setText("100%");
                }
            }
        });
    }
    //点击返回上一页面而不是退出浏览器
    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }
    //销毁Webview
    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null,null);
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>