The use of Android native WebView

Time:2021-6-21
The use of Android native WebView

Android WebView is a special view on Android platform, which is used to display web pages. This WebView class can be used to display an online web page, and of course, it can also be used to develop browsers.
The internal implementation of WebView uses WebKit to display the content of the view, providing web page forward and backward, web page zoom in, zoom out, search and other functions
WebView is a control based on WebKit engine to display web pages. Android WebView adopts different WebKit kernel versions in low and high versions.
1: The use of WebView
1. Add WebView control to layout file
2. Let WebView control load and display web page in code
Add permission:
<uses-permission android:name=”android.permission.INTERNET” />

public class WebViewActivity extends AppCompatActivity {
    private WebView web_view;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_web);
 web_view=findViewById(R.id.web_view);
 //White edge problem solving
web_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
 web_ view.loadUrl(" http://www.baidu.com ");// Jump to Baidu page of browser
  //The system will open the web page through the mobile browser by default. In order to display the web page directly through WebView, it must be set
 web_view.setWebViewClient(new WebViewClient(){
    @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
        //Using WebView to load display URL
 view.loadUrl(url);
 //Return true
 return true;
 }
});
 }
}

Common methods of WebView
//Restore pausetimers state
1.web_view.resumeTimers();
//It will pause the layout display, parsing and delay of all webviews, thus reducing CPU power consumption
2.web_view.pauseTimers();
//Activate WebView to be active, and the response of the web page can be executed normally
3.web_view.onResume();
//When the page is out of focus and switched to the background invisible state, you need to execute onpause ()
//The onpause () action notifies the kernel to pause all actions, such as DOM parsing, JavaScript execution, etc
4.web_view.onPause();
//When WebView calls destory, WebView is still bound to activity
//This is because the context object of the activity is passed in when the custom WebView is built
//Therefore, you need to remove the WebView from the parent container before destroying it
rootLayout.removeView(web_view);
5.web_view.destroy();
//Can I go back
6.web_view.canGoBack()
//Back page
7.web_view.goBack()
//Can we move forward
8.web_view.canGoForward()
//Forward page
9.web_view.goForward()
//Clear cache left by page access
//Because the kernel cache is global, this method is not only for WebView, but for the whole application
10.web_view.clearCache(true);
//Clear the history of current WebView access
//Only WebView will access all records in the history except the current access record
11.web_view.clearHistory();
//This API only clears the form data that is automatically filled, and does not clear the data stored locally by WebView
12.web_view.clearFormData();

@Override
protected void onPause() {
    super.onPause();
 web_view.onPause();
 //It will pause the layout display, parsing and delay of all webviews, thus reducing CPU power consumption
 web_view.pauseTimers();
}

@Override
protected void onDestroy() {
    if (web_view!=null){
        web_view.clearHistory();
 ViewGroup parent = (ViewGroup) web_view.getParent();
 parent.removeView(web_view);
 web_view.destroy();
 web_view=null;
 Log. D ("AA", "WebView is not empty");
 }
    Log. D ("AA", "WebView is empty");
 super.onDestroy();
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode==KEYCODE_BACK&&web_view.canGoBack()){
        web_view.goBack();
 return true; }
    return super.onKeyDown(keyCode, event);
}

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

WebView client is used to handle various notification and request events.

  • Onpagestarted(): called when the page starts to load. At this time, the loading progress bar can be displayed to make the user wait patiently for the page to load.
  • Onpagefinished(): called when the page has finished loading. At this time, the loading progress bar can be hidden to remind the user that the page has finished loading.
  • Onloadresource(): called every time a page loads a resource.
  • Shouldoveverrideurlloading(): WebView loading URL will call the system browser by default. By rewriting this method, the page loading can be completed in the current application.
  • Onreceivederror(): called when there is an error in page loading. At this time, you can jump to the user-defined error reminder page, which is more beautiful than the default error page of the system and optimizes the user experience.
  • Onreceivedhttperror(): an error occurred while loading the page request.
  • Onreceivedslerror(): an error occurred while the page was loading resources.
  • Shouldoveverridekeyevent(): the default response event of the key is overridden. At this time, you can add the corresponding logic when you click some keys according to your own needs.
  • Onscalechanged(): called when the scale of the page changes. At this time, you can adjust the content displayed in the WebView according to the current scale, such as modifying the font size, image size, etc.
  • Shouldinterceptrequest(): you can judge whether you need to intercept a request according to the content of the request.
WebViewClient webViewClient=new WebViewClient(){
    @Override
 public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        //When the page starts to load, the specific loading implementation is called
 }
    @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
 return true; }
};

3: Webchromeclient class
This class is used to handle website icons, website titles, website pop ups, etc. the following are related methods

  • Onprogresschanged(): called when the page loading progress changes. This method can feed back the loading status to the user in real time, such as displaying the progress bar.
  • Onreceiveicon(): receives the icon of a web page. You can use this method to set the icon on a native control, such as toolbar.
  • Onreceivedtitle(): receives the title of a web page. You can use this method to set the icon on a native control, such as toolbar.
  • Onjsalert(): handles the alert dialog box of JS.
  • Onjsprompt(): handles the prompt dialog box of JS.
  • Onjsconfirm(): process the confirm dialog box of JS.
  • Onpermissionrequest(): called when a web page requests Android permissions.
  • Onpermissionrequestcancelled(): called when the web page requests Android permission to be cancelled.
  • Onshowfilechooser(): called when a web page uploads a file.
  • Getvideoloadingprogressview(): customize the progress bar when playing and loading media files.
  • Getdefaultvideoposter(): sets the default preview of media files.
  • Onshowcustomview(): called when the media file enters full screen.
  • Onhidecustomview(): called when the media file exits the full screen.
WebChromeClient webChromeClient=new WebChromeClient(){
    @Override
 public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress<100){
            String progress=newProgress+"%";
 tv_progress.setText(progress);
 }else {
            tv_progress.setText("100%");
 }
    }
    @Override
 public void onReceivedTitle(WebView view, String title) {
        tv_title.setText(title);
 }
};

4: Configuration of websettings control

WebSettings webSettings = webView.getSettings();

webSettings.setJavaScriptEnabled(true); ->  Is JS support enabled
webSettings.setPluginsEnabled(true); ->  Is plug-in support enabled
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); ->  Allow JS to open a new window

webSettings.setUseWideViewPort(true); ->  Zoom to screen size
webSettings.setLoadWithOverviewMode(true); ->  Zoom to screen size
webSettings.setSupportZoom(true); ->  Is scaling supported
webSettings.setBuiltInZoomControls(true); ->  Whether zoom is supported, provided that zoom is supported
webSettings.setDisplayZoomControls(false); ->  Hide scale control

webSettings.setAllowFileAccess(true); ->  Allow access to files
webSettings.setDomStorageEnabled(true); ->  Node cache
webSettings.setDatabaseEnabled(true); ->  Data cache
webSettings.setAppCacheEnabled(true); ->  Apply cache
webSettings.setAppCachePath(uri); ->  Set cache path

webSettings.setMediaPlaybackRequiresUserGesture(false); ->  Do you want gestures to trigger media
webSettings.setStandardFontFamily("sans-serif"); ->  Format font library
webSettings.setFixedFontFamily("monospace"); ->  Format font library
webSettings.setSansSerifFontFamily("sans-serif"); ->  Format font library
webSettings.setSerifFontFamily("sans-serif"); ->  Format font library
webSettings.setCursiveFontFamily("cursive"); ->  Format font library
webSettings.setFantasyFontFamily("fantasy"); ->  Format font library
webSettings.setTextZoom(100); ->  Sets the percentage of text scaling
webSettings.setMinimumFontSize(8); ->  Set the minimum value of text font (1-72)
webSettings.setDefaultFontSize(16); ->  Set the default size of the text font

webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_ COLUMN); ->  Rearrange by rules
webSettings.setLoadsImagesAutomatically(false); ->  Do you want to load pictures automatically
webSettings.setDefaultTextEncodingName("UTF-8"); ->  Format encoding
webSettings.setNeedInitialFocus(true); ->  Need to get focus
webSettings.setGeolocationEnabled(false); ->  Set to open the positioning function
webSettings.setBlockNetworkLoads(false); ->  Get resources from the network

example:

public class WebViewActivity extends AppCompatActivity {
    private WebView web_view;
 private TextView tv_title,tv_start,tv_progress,tv_end;
 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_web);
 web_view=findViewById(R.id.web_view);
 tv_title=findViewById(R.id.tv_title);
 tv_start=findViewById(R.id.tv_start);
 tv_progress=findViewById(R.id.tv_progress);
 tv_end=findViewById(R.id.tv_end);
 web_ view.loadUrl(" http://www.baidu.com ");// HTTP requests the HTTP that needs to be configured on Android 9.0
 //White edge problem solving
 web_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
 web_view.setWebViewClient(webViewClient);
 web_view.setWebChromeClient(webChromeClient);
 }
    WebViewClient webViewClient=new WebViewClient(){
        @Override
 public void onPageStarted(WebView view, String url, Bitmap favicon) {
           tv_ Start. Settext ("start loading!");
 }
        @Override
 public void onPageFinished(WebView view, String url) {
            tv_ End. Settext ("loading completed");
 }
        @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
 return true; }
    };
 WebChromeClient webChromeClient=new WebChromeClient(){
        @Override
 public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress<100){
                String progress=newProgress+"%";
 tv_progress.setText(progress);
 }else {
                tv_progress.setText("100%");
 }
        }
        @Override
 public void onReceivedTitle(WebView view, String title) {
            tv_title.setText(title);
 }
    };
 @Override
 protected void onPause() {
        super.onPause();
 web_view.onPause();
 //It will pause the layout display, parsing and delay of all webviews, thus reducing CPU power consumption
 web_view.pauseTimers();
 }
    @Override
 protected void onDestroy() {
        if (web_view!=null){
            web_view.clearHistory();
 ViewGroup parent = (ViewGroup) web_view.getParent();
 parent.removeView(web_view);
 web_view.destroy();
 web_view=null;
 Log. D ("AA", "WebView is not empty");
 }
        Log. D ("AA", "WebView is empty");
 super.onDestroy();
 }
    @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KEYCODE_BACK&&web_view.canGoBack()){
            web_view.goBack();
 return true; }
        return super.onKeyDown(keyCode, event);
 }
}

5: About JS calling Android

WebSettings webSettings=web_view.getSettings();
//Set permissions to interact with JS
webSettings.setJavaScriptEnabled(true);
//Setting to allow JS pop ups
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
web_ view.addJavascriptInterface(new AndroidJS(this),"android");// Mapping objects

Write an androidjs class

public class AndroidJS {
    private Context context;
 public AndroidJS(Context context) {
        this.context = context;
 }
    @JavascriptInterface
 public void callFinish() {
        Log. D ("AA", "JS call");
 Log.i("callFinish", "Thread:" + Thread.currentThread());
 }
}
//Callfinish() is called by JS in Android. Callfinish(); Android is the key I pass in. It is mapped to the object of JS mapping class. The name can be taken at will. Just keep it consistent

There are three ways to call Android for JS
1. PassedWebViewOfaddJavascriptInterface()Mapping objects (no problem)
2. AdoptionWebViewClientOfshouldOverrideUrlLoading ()Method callback intercepts the URL (if there is a problem, it reports “referenceerror: Android is not defined”)
3. AdoptionWebChromeClientOfonJsAlert()onJsConfirm()onJsPrompt()Method callback intercepts JS dialog boxalert()confirm()prompt()Message (no attempt)
There are two ways to call JS for Android
1. Through the loadurl ()
2. Through the evaluatejavascript ()

//Android version variables
final int version = Build.VERSION.SDK_INT;
//Because this method can only be used in Android version 4.4, it is necessary to judge the version
if (version<18){
    web_ View. Loadurl ("URL connection")// Pass in the corresponding URL,
}else {
    web_ View. Evaluatejavascript ("URL connection", new valuecallback < string > (){
        @Override
 public void onReceiveValue(String value) {
            //Here is the result returned by JS
 }
    });
}

Ending: the strong are fearless