Android Webview usage guide

How to load url:

1. Load a web page:
webView.loadUrl("https://www.baidu.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");

Copy the code

WebView forward and backward:

// Can I back up
Webview.canGoBack();
// Back up the page
Webview.goBack();
// Whether can advance
Webview.canGoForward();
// Forward the page
 Webview.goForward();

// Use the current index as the starting point to move forward or backward to the steps specified in the history
// If steps is negative, steps are backward, and positive steps are forward
Webview.goBackOrForward(intsteps);
Copy the code

Common handling of web page backs:

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


    @Override
    public void onBackPressed(a) {
        
        if (webView.canGoBack()) {
            webView.goBack();
            return;
        }

        super.onBackPressed();

    }
Copy the code

Clear cache:

		// Clear the cache left by web page visits
        Since the kernel cache is global, this method applies not only to the WebView but to the entire application.
        Webview.clearCache(true);

        // Clears the history of the current WebView access
        // Only webView will access all records in the history except the current access record
        Webview.clearHistory();

        // This API only cleans up auto-filled form data, not WebView data stored locally
        Webview.clearFormData();
Copy the code

WebView configuration:

 		WebSettings webSettings = webView.getSettings();
        / / support javascript
        webSettings.setJavaScriptEnabled(true);
        / / the plugin
        webSettings.setPluginState(WebSettings.PluginState.ON);
        // Set up the adaptive screen
        webSettings.setUseWideViewPort(true);
        // Zoom to the size of the screen
        webSettings.setLoadWithOverviewMode(true);
        // Whether the zoom operation is supported
        webSettings.setSupportZoom(false);
        // Set the built-in zoom control. If false, the WebView is not scalable
        webSettings.setBuiltInZoomControls(false);
        // Hide the native zoom control
        webSettings.setDisplayZoomControls(true);
        LayoutAlgorithm.NARROW_COLUMNS ADAPTS to content size. LayoutAlgorithm
        // 2, layoutalgORITHm. SINGLE_COLUMN: ADAPTS to the screen, the content will automatically scale
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // Set whether the WebView supports multiple Windows
        webSettings.setNeedInitialFocus(true);
        // Set the DOM Storage cache
        webSettings.setDomStorageEnabled(true);
        // Set the cache policy
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // Set access to files
        webSettings.setAllowFileAccess(true);
        // Support to open new Windows through JS
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // Support to open new Windows through JS
        webSettings.setLoadsImagesAutomatically(true);
        // Set the encoding format
        webSettings.setDefaultTextEncodingName("utf-8");
        // Request focus
        webView.requestFocusFromTouch();
        // Disable a blank space at the top of the page and then automatically go back
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);
Copy the code

WebViewClient:

	webView.setWebViewClient(new WebViewClient() {
            
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                // When the page starts loading
            }
  
            @Override
            public void onPageFinished(WebView view, String url) {
                // When the page is finished loading
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
                // Whether the URL needs to be blocked during the jump
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                // When loading error}});Copy the code

WebChromeClient

 	webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                // Page loading progress
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                // Get the web title
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
                // a js dialog box is displayed}});Copy the code

Android calls js methods:

1、通过loadUrl();

 String token = getToken();
// Call getToken
 webView.loadUrl("javascript:getToken('" + token + "')");
Copy the code

EvaluateJavascript ();

This method is more efficient than the first method, because execution of this method does not refresh the page, whereas execution of the first method (loadUrl) does. This method is not available until Android 4.4.

WebView. EvaluateJavascript ("javascript:getToken('" + token + "')".new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String value) {
            // This is the result returned by js}}); }Copy the code

Complete code

public class WebViewActivity extends AppCompatActivity {

    private ImageView ivBack;
    private TextView tvClose;
    private TextView tvTitle;
    private WebView webView;
    private ProgressBar progress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Go to title bar
        if(getSupportActionBar() ! =null) {
            getSupportActionBar().hide();
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        }
        setContentView(R.layout.activity_webview);

        init();
    }

    private void init(a) {
        initView();
        initWebView();
        loadUrl();
        setWebViewClient();
        setWebChromeClient();
        
    }


    private void initView(a) {
        ivBack = (ImageView) findViewById(R.id.iv_web_head_back);
        tvClose = (TextView) findViewById(R.id.tv_web_head_close);
        tvTitle = (TextView) findViewById(R.id.tv_web_head_title);
        progress = (ProgressBar) findViewById(R.id.pb_web_progress);
        webView = (WebView) findViewById(R.id.ev_web);

        tvClose.setVisibility(View.INVISIBLE);
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView(a) {
        WebSettings webSettings = webView.getSettings();
        / / support javascript
        webSettings.setJavaScriptEnabled(true);
        / / the plugin
        webSettings.setPluginState(WebSettings.PluginState.ON);
        // Set up the adaptive screen
        webSettings.setUseWideViewPort(true);
        // Zoom to the size of the screen
        webSettings.setLoadWithOverviewMode(true);
        // Whether the zoom operation is supported
        webSettings.setSupportZoom(false);
        // Set the built-in zoom control. If false, the WebView is not scalable
        webSettings.setBuiltInZoomControls(false);
        // Hide the native zoom control
        webSettings.setDisplayZoomControls(true);
        LayoutAlgorithm.NARROW_COLUMNS ADAPTS to content size. LayoutAlgorithm
        // 2, layoutalgORITHm. SINGLE_COLUMN: ADAPTS to the screen, the content will automatically scale
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // Set whether the WebView supports multiple Windows
        webSettings.setNeedInitialFocus(true);
        // Set the DOM Storage cache
        webSettings.setDomStorageEnabled(true);
        // Set the cache policy
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // Set access to files
        webSettings.setAllowFileAccess(true);
        // Support to open new Windows through JS
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // Support to open new Windows through JS
        webSettings.setLoadsImagesAutomatically(true);
        // Set the encoding format
        webSettings.setDefaultTextEncodingName("utf-8");
        // Request focus
        webView.requestFocusFromTouch();
        // Disable a blank space at the top of the page and then automatically go back
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);


    }


    private void setWebViewClient(a) {


        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                // When the page starts loading
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // When the page is finished loading
                if (webView.canGoBack()) {
                    // You can now return with the display closed
                    tvClose.setVisibility(View.VISIBLE);
                } else{ tvClose.setVisibility(View.GONE); }}@Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // Whether the URL needs to be blocked during the jump

                return super.shouldOverrideUrlLoading(view, url);

            }


            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String
                    failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                // When loading error}}); }private void setWebChromeClient(a) {

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                // Page loading progress

                if (progress == null) {
                    return;
                }

                if (newProgress == 100) {
                    progress.setVisibility(View.GONE);// The progress bar disappears after loading the page
                } else {
                    progress.setVisibility(View.VISIBLE);// A progress bar is displayed when the page starts loading
                    progress.setProgress(newProgress);// Set the progress value}}@Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                // Get the web title

                if (!TextUtils.isEmpty(title)) {
                    tvTitle.setText(title);
                }

            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
                // a js dialog box is displayed}}); }protected void loadUrl(a) {  
       String url = "https://www.baidu.com/";
        webView.loadUrl(url);

    }


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


    @Override
    public void onBackPressed(a) {

        handleBack();

    }


    /** * process the return key */
    private void handleBack(a) {

        if(webView ! =null && webView.canGoBack()) {
            webView.goBack();
        } else{ finish(); }}@Override
    protected void onDestroy(a) {
        super.onDestroy();
        if(webView ! =null) { webView.destroy(); }}}Copy the code

About native js interaction:

H5 modules have been used a lot in recent projects and interact with native modules a lot. Went through some data and found some third-party libraries.

JsBridge

WebViewJavascriptBridge(recommended)

Information:

AgentWeb, an easy-to-use Android Web library

WebView deep learning (1) The basic use of WebView and Android and JS interaction

WebView encountered pit and optimization

The webView intercepts the js alert method to convert to a native dialog

Talk about WebView and JS interaction scheme – Android & iOS