Android Getting Started tutorial | WebView

Posted by journeyman73 on Tue, 07 Dec 2021 17:41:40 +0100

WebView usage

Disable webview from processing long press events

Set OnLongClickListener to consume long press events.

web.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        return true;
    }
});

size of font changing

Enumeration of font sizes.

    public static enum TextSize {
        SMALLEST(50),
        SMALLER(75),
        NORMAL(100),
        LARGER(125),
        LARGEST(150);

        int value;

        private TextSize(int var3) {
            this.value = var3;
        }
    }

Get the WebSettings and set the font size.

WebSettings st = wv.getSettings();
st.setTextSize(WebSettings.TextSize.LARGER);

Display html text

Example: the HTML text used in the example is the same as the HTML text displayed by TextView.

private static final String T1 = "<p>Tell me the <font color=\"red\">color</font></p>";
private static final String H1 = "<p>Tell me the <text style=\"color: blue; font-weight: bold;\">color</text>.</p>";
private static final String H1_FIX = "<p>Tell me the <b><font color=\"blue\">color</font></b>.</p>";
​
 wb1.loadData(T1, "text/html", "UTF-8");
 wb2.loadData(H1, "text/html", "UTF-8");
 wb3.loadData(H1_FIX, "text/html", "UTF-8");

Place WebView in layout

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

WebView display Html text rendering

Previously, TextView could not display color and bold H1, which can be displayed normally in webView.

The above loadData method specifies that the mimeType is text/html and the encoding type is UTF-8.

WebView loadData Chinese garbled code

Chinese garbled code occurs when using loadData.

String htmlData = "<p>This is me. I'm text Text.</p>";
webView.loadData(htmlData, "text/html", "UTF-8"); // Some models have Chinese garbled codes

Use the loadDataWithBaseURL method to avoid Chinese garbled code.

webView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);

WebView loads web pages in assets

We put the web page file in the assets directory.

Set Web settings, allow reading files, and so on.

The path to the assets directory is file:///android_ Start with asset /.

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

String url = "file:///android_asset/drag-to/index.html";
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowContentAccess(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);

WebView FAQ

1. Optimize the loading speed when loading resources in webView (mainly for pictures)

Reason: after the html code is downloaded to the WebView, the webkit starts to parse each node of the web page. When an external style file or external script file is found, it will asynchronously initiate a network request to download the file. However, if it is also parsed to the image node before that, it will also initiate a network request to download the corresponding image. In the case of poor network conditions, too many network requests will cause bandwidth tension, affect the time of css or js file loading, and cause page blank loading for too long.

Solution: tell WebView not to automatically load the picture first, and then start the picture loading after the page is finish ed.

//Set during initialization. The specific code is in the WebView class
if(Build.VERSION.SDK_INT >= KITKAT) {
    //Set the page not to load pictures temporarily when loading
    webView.getSettings().setLoadsImagesAutomatically(true);} else {
    webView.getSettings().setLoadsImagesAutomatically(false);}

/**
 * This method is called when the page is loaded
 * @param view  view
 * @param url  url link
 */
@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    //Launch the image loading after the page is finish ed
    if(!webView.getSettings().getLoadsImagesAutomatically()) {
        webView.getSettings().setLoadsImagesAutomatically(true);
    }
}

2.WebView hardware acceleration causes page rendering flicker

Reason: for systems above 4.0, after we turn on hardware acceleration, WebView renders pages faster and drags more smoothly. However, one side effect is that when the WebView is covered by the whole and then suddenly restored (for example, when sliding the WebView out of the side using the SlideMenu), white blocks will appear in this transition period and the interface will flash.

Solution: temporarily shut down the hardware acceleration of WebView before the transition period, and then turn it on after the transition period.

//Turn off hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
//Turn on hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {    webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}

3. The loading progress bar can be displayed in advance
Reason: WebView.loadUrl("url") will not immediately call back onPageStarted or onProgressChanged, because during this time period, WebView may be initializing the kernel or establishing a connection with the server. During this time period, white screen is easy to appear, and the white screen user experience is very bad.

Solution: although displaying the progress bar in advance does not improve performance, it is also very important for the user experience.

//correct
pb.setVisibility(View.VISIBLE);
mWebView.loadUrl("https://github.com / "); / / not very good
@Override
public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
    super.onPageStarted(webView, s, bitmap);
    //Set the operation at the beginning of loading
    pb.setVisibility(View.VISIBLE);
}

//The following is the logic to monitor the progress change of the progress bar
mWebView.getWebChromeClient().setWebListener(interWebListener);
mWebView.getWebViewClient().setWebListener(interWebListener);
private InterWebListener interWebListener = new InterWebListener() {
    @Override
    public void hindProgressBar() {
        pb.setVisibility(View.GONE);
    }

    @Override
    public void showErrorView() {

    }

    @Override
    public void startProgress(int newProgress) {
        pb.setProgress(newProgress);
    }

    @Override
    public void showTitle(String title) {

    }
};

4. WebView password plaintext storage vulnerability optimization

Reason: WebView turns on the password saving function mWebView.setSavePassword(true) by default. If this function is not turned off, a prompt box will pop up when the user enters the password to ask whether to save the password. If "yes" is selected, the password will be plaintext saved to / data / com.package.name/databases/webview.db, which is in danger of being stolen.

Solution: turn off the password saving reminder function through WebSettings.setSavePassword(false).

//Set whether to enable the password saving function. It is not recommended to enable it. It has been processed by default, and there is a risk of stealing the password
WebView.setSavePassword(false);

5. Customize the status page of loading exception error. For example, error may appear in the following methods

Cause: when WebView loads an error page (usually 404 not found), Android WebView will display an error interface by default. When WebView loads an error, it will receive an error in onReceivedError() 'and onReceivedTitle method in WebViewClient instance.

Solution: customize the error page style.

/**
 * An error occurred while requesting the network
 * @param view                              view
 * @param errorCode                         error
 * @param description                       description
 * @param failingUrl                        Failed link
 */
@Override
public void onReceivedError(WebView view, int errorCode, String description, String
        failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);
    if (errorCode == 404) {
        //Hiding 404 page information defined by the system with javascript
        String data = "Page NO FOUND!";
        view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\"");
    } else {
        if (webListener!=null){
            webListener.showErrorView();
        }
    }
}

// Report Web resource load errors to the host application. These errors usually indicate that you cannot connect to the server.
// It is worth noting that the difference is the callback of the outdated version, and the new version will be called any resource (iframe, image, etc.)
// Not just the home page. Therefore, it is recommended to perform the minimum required work during the callback process.
// After 6.0
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    super.onReceivedError(view, request, error);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        X5WebUtils.log("Server exception"+error.getDescription().toString());
    }
    //ToastUtils.showToast("after server exception 6.0");
    //When loading errors, let it load the local error web page file
    //mWebView.loadUrl("file:///android_asset/errorpage/error.html");
    if (webListener!=null){
        webListener.showErrorView();
    }
}

/**
 * This method is mainly used to monitor the operation of title change
 * @param view  view
 * @param title title
 */
@Override
public void onReceivedTitle(WebView view, String title) {
    super.onReceivedTitle(view, title);
    if (title.contains("404") || title.contains("The web page cannot be opened")){
        if (webListener!=null){
            webListener.showErrorView();
        }
    } else {
        // Set title
    }
}

[Android zero foundation tutorial video reference]

Topics: Android