1024programmer Blog Android: This is a comprehensive and detailed guide to using Webview_April Human V’s Blog

Android: This is a comprehensive and detailed guide to using Webview_April Human V’s Blog

Foreword

  • Many App now have built-in Web pages (Hybrid App), such as many e-commerce platforms, such as Taobao, JD.com, Juhuasuan, etc. As shown below

    Jingdong Homepage

  • So how can this be achieved? In fact, this is the implementation of a WebView component in Android

  • Today, I will present a comprehensive introduction to common uses of WebView.


Table of Contents

Article directory


1. Introduction

WebView is a control based on the webkit engine to display web pages.

Android’s Webview adopts different webkit version kernels in low and high versions, and directly uses Chrome after 4.4.


2. Function

  • Display and render web pages
  • Directly use html files (on the network or in local assets) for layout
  • Can be called interactively with JavaScript

The WebView control is powerful. In addition to the properties and settings of the general View, it can also perform powerful processing on url requests, page loading, rendering, and page interaction.


3. Introduction

Generally speaking, Webview can be used alone or in conjunction with its tools, so next, I will introduce:

  • Common methods of the Webview class itself
  • The most commonly used tool classes of Webview: WebSettings class, WebViewClient class, WebChromeClient class
  • Interaction between Android and Js

3.1 Common methods of Webview class

3.1.1 Load URL

The loading method is divided into three types according to the resources


   //Method 1. Load a web page:
   webView.loadUrl("http://www.google.com/");

   //Method 2: Load the html page in the apk package
   webView.loadUrl("file:///android_asset/test.html");

   //Method 3: Load the local html page of the mobile phone
    webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html");

    // Method 4: Load a small part of the HTML page
   WebView.loadData(String data, String mimeType, String encoding)
 // Parameter Description:
 // Parameter 1: The content to be intercepted and displayed
 // The four characters '#', '%', '\' and '?' cannot appear in the content. If they appear, they must be replaced by %23, %25, %27, %3f, otherwise an exception will occur
 // Parameter 2: the type of display content
 // parameter 3: bytecode


 

3.1.1 Status of WebView

//Activate the WebView as an active state, and can normally execute the response of the web page
 webView.onResume();

 //When the page loses focus and is switched to the background invisible state, onPause needs to be executed
 //Notify the kernel to suspend all actions through the onPause action, such as DOM analysis, plugin execution, and JavaScript execution.
 webView.onPause();

 //When the application (with webview) is switched to the background, this method is not only for the current webview but for the global application-wide webview
 //It will pause all webview's layout, parsing, javascripttimer.  Reduce CPU power consumption.
 webView. pauseTimers()
 //Restore pauseTimers state
 webView. resumeTimers();

 //Destroy Webview
 //When the Activity is closed, if the music or video of the Webview is still playing.  You must destroy the Webview
 //But note: when webview calls destroy, webview is still bound to Activity
 //This is because the context object of the Activity is passed in when the custom webview is built
 //So you need to remove the webview from the parent container first, and then destroy the webview:
 rootLayout. removeView(webView);
 webView.destroy();
 

3.1.2 About Forward/Back Page

//Is it possible to go back
 Webview. canGoBack()
 //back page
 Webview. goBack()

 // can move forward
 Webview. canGoForward()
 // forward page
 Webview. goForward()

 //Take the current index as the starting point to move forward or backward to the steps specified in the history
 //If steps is negative, it is backward, and if it is positive, it is forward
 Webview.goBackOrForward(intsteps)
 

Common usage: Back key to control web page back

  • Problem: Without any processing, click the “Back” button of the system when browsing the webpage, and the entire Browser will call finish() to end itself
  • Goal: After clicking back, the webpage is rolled back instead of launching the browser
  • Solution: Process and consume the Back event in the current Activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if ((keyCode == KEYCODE_BACK) && mWebView. canGoBack()) {
         mWebView.goBack();
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }
 

3.1.3 Clear cache data

//Clear the cache left by web page access
 //Since the kernel cache is global, this method is not only for the webview but for the entire application.
 Webview.clearCaStart & end and get loading progress
 
  • Specific implementation:
  • Step 1: Add network access

    This is the premise! This is the premise! This is the premise!

    AndroidManifest.xml

    
     

    Step 2: Main Layout
    activity_main.xml

    
     
    
    
        
         
    
         
         
    
         
         
    
         
         
        
         
         
     
    
     

    Step 3: Use the corresponding subclass and its method according to the required function (the annotation is very clear)
    MainActivity.java

    package com.example.carson_ho.webview_demo;
    
     import android.graphics.Bitmap;
     import android.os.Bundle;
     import android.support.v7.app.AppCompatActivity;
     import android.view.KeyEvent;
     import android.view.ViewGroup;
     import android.webkit.WebChromeClient;
     import android.webkit.WebSettings;
     import android.webkit.WebView;
     import android.webkit.WebViewClient;
     import android.widget.TextView;
    
    
     public class MainActivity extends AppCompatActivity {
         WebView mWebview;
         WebSettings mWebSettings;
         TextView beginLoading, endLoading, loading, mtitle;
    
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R. layout. activity_main);
    
    
             mWebview = (WebView) findViewById(R.id.webView1);
             beginLoading = (TextView) findViewById(R.id.text_beginLoading);
             endLoading = (TextView) findViewById(R.id.text_endLoading);
             loading = (TextView) findViewById(R.id.text_Loading);
             mtitle = (TextView) findViewById(R.id.title);
    
             mWebSettings = mWebview.getSettings();
    
             mWebview.loadUrl("http://www.baidu.com/");
    
            
             //The setting does not need to be opened by the system browser, and it will be displayed directly in the current Webview
             mWebview.setWebViewClient(new WebViewClient() {
                 @Override
                 public boolean shouldOverrideUrlLoading(WebView view, String url) {
                     view.loadUrl(url);
                     return true;
                 }
             });
    
             //Set the WebChromeClient class
             mWebview.setWebChromeClient(new WebChromeClient() {
    
    
                 //Get the website title
                 @Override
                 public void onReceivedTitle(WebView view, String title) {
                     System.out.println("The title is here");
                     mtitle.setText(title);
                 }
    
    
                 // get loading progress
                 @Override
                 public void onProgressChanged(WebView view, int newProgress) {
                     if (newProgress < 100) {
                         String progress = newProgress + "%";
                         loading.setText(progress);
                     } else if (newProgress == 100) {
                         String progress = newProgress + "%";
                         loading.setText(progress);
                     }
                 }
             });
    
    
             //Set the WebViewClient class
             mWebview.setWebViewClient(new WebViewClient() {
                 //Set the function before loading
                 @Override
                 public void onPageStarted(WebView view, String url, Bitmap favicon) {
                     System.out.println("Start loading");
                     beginLoading.setText("start loading");
    
                 }
    
                 //Set the end loading function
                 @Override
                 public void onPageFinished(WebView view, String url) {
                     endLoading.setText("end loading");
    
                 }
             });
         }
    
         //Click to return to the previous page instead of exiting the browser
         @Override
         public boolean onKeyDown(int keyCode, KeyEvent event) {
             if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
                 mWebview.goBack();
                 return true;
             }
    
             return super.onKeyDown(keyCode, event);
         }
    
         //Destroy Webview
         @Override
         protected void onDestroy() {
             if (mWebview != null) {
                 mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
                 mWebview. clearHistory();
    
                 ((ViewGroup) mWebview. getParent()). removeView(mWebview);
                 mWebview.destroy();
                 mWebview = null;
             }
             super. onDestroy();
         }
     }
    
     

    Demo address

    Source code: Carson_Ho's Github-WebviewDemo


    5. Summary

    • This article provides a comprehensive introduction to Webview, summarized as follows

    Schematic diagram

    https://www.jianshu.com/p/3c94ae673e2a

    icon) {
    System.out.println("Start loading");
    beginLoading.setText("start loading");

    }

    //Set the end loading function
    @Override
    public void onPageFinished(WebView view, String url) {
    endLoading.setText("end loading");

    }
    });
    }

    //Click to return to the previous page instead of exiting the browser
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
    mWebview.goBack();
    return true;
    }

    return super.onKeyDown(keyCode, event);
    }

    //Destroy Webview
    @Override
    protected void onDestroy() {
    if (mWebview != null) {
    mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
    mWebview. clearHistory();

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

    Demo address

    Source code: Carson_Ho’s Github-WebviewDemo


    5. Summary

    • This article provides a comprehensive introduction to Webview, summarized as follows

    Schematic diagram

    https://www.jianshu.com/p/3c94ae673e2a

    This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/android-this-is-a-comprehensive-and-detailed-guide-to-using-webview_april-human-vs-blog/

    author: admin

    Previous article
    Next article

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Contact Us

    Contact us

    181-3619-1160

    Online consultation: QQ交谈

    E-mail: [email protected]

    Working hours: Monday to Friday, 9:00-17:30, holidays off

    Follow wechat
    Scan wechat and follow us

    Scan wechat and follow us

    Follow Weibo
    Back to top
    首页
    微信
    电话
    搜索