Android study notes: WebView

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/MaybeForever/article/details/96431439

Project address : https: //github.com/ambition-hb/WebViewDemo


First, set the basic properties of the controls WebView

method Explanation
WebView.getSettings().setJavaScriptEnable(boolean enabled) Expressed support js, js if want to be able to interact with Java, you can be set to true
WebView.getSettings().setSupportZoom(boolean enabled) Expressed support scaling, the default is true
WebView.getSettings().setBuiltInZoomControls(boolean enabled) Set whether to display the Zoom tool defaults to false
WebView.getSettings().setDefaultFontSize(int size) Sets the default font size, default is 16, the effective range is 1 to 72
WebView.getSettings().setLayoutAlgorithm(LayoutoAlgorithm.SINGLE_COLUMN) Set web content re-layout mode, the screen adaptation of web pages for setting the rules

Two, WebView basis of usage

WebView a new item, then modify the code activity_main.xml layout file, as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.haobi.webviewdemo.MainActivity">

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

</LinearLayout>

Then, in MainActivity modify the code as follows:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1、使用findViewById()方法获取到WebView的实例
        WebView webView = (WebView)findViewById(R.id.web_view);
        //2、调用WebView的getSettings()方法去设置一些浏览器的属性
        //setJavaScriptEnabled()方法用于设置是否执行页面的js方法
        webView.getSettings().setJavaScriptEnabled(true);
        //3、调用WenView的setWebViewClient()方法并传入一个WebViewClient的实例
        //作用在于网页跳转的时候,目标页面仍在当前WebView中显示,而不是打开系统浏览器
        webView.setWebViewClient(new WebViewClient());
        //4、调用WebView的loadUrl()方法并将网址传入
        webView.loadUrl("http://www.baidu.com");
    }
}

Finally, request permission to join the network in the AndroidManifest.xml file.

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

Three, WebView use advanced

1、WebViewClient

WebViewClient is a helper class WebView, we often use WebViewClient this class to monitor state webview to load the page .

The following is the way we often use in development.

  • onLoadResource

    Web page load callback various resources, such as your web page using a variety of images and css files js files

  • onPageStarted

    We begin loading the page callback

  • onPageFinished

    Page load completion callback

  • onReceivedError(WebView view, int errorCode, String description, String failingUrl)

    Page load callback failure, if it is running at 6.0 phone, you need to onReceivedError (WebView, WebResourceRequest, WebResourceError)

  • shouldOverrideUrlLoading

    The process jumps inside pages

2、WebChromeClient

We often use WebChromeClient this class to handle interaction with the web content js class

  • onJsAlert

    Receiving the alert event pages

  • onJsPrompt

    Pages prompt input box to receive event

  • onJsConfirm

    Pages confirm receiving acknowledgment event

  • onProgressChanged

    The percentage of page load

  • onReceivedIcon

    Receiving the page icon

  • onReceivedTitle

    The title page of reception

3、WebSettings

WebSettings is provided WebView class can be set to various detailed webview parameters .

  • setAllowFileAccess(boolean allow)

    Set whether to use file access protocols pages, often used to access assets and raw folder following pages

  • setBuiltInZoomControls(boolean enabled)

    Set whether to use the zoom feature that comes with webview

  • setDatabaseEnabled(boolean flag)

  • setDomStorageEnabled(boolean flag);

    Setting is enough to support database features of html5

  • setDefaultFontSize(int size)

    Text size settings page

  • setJavaScriptEnabled(boolean flag)

    Set whether to perform page js method

  • setCacheMode

    Set the return key process, whether to use the cache page is loaded, LOAD_DEFAULT (start with the cache load, did not go to network load), LOAD_CACHE_ELSE_NETWORK (start with the cache load, did not go to network load), LOAD_NO_CACHE (do not use cache), LOAD_CACHE_ONLY (only use cache)

4、WebView

Android controls provided, able to load Web pages and html data.

  • addJavascriptInterface(Object object, String name)

    A target to increase the webview allow java code to interact with js

  • loadUrl(String url)

    Loading a web page, web pages can be, but also to load local pages, local pages using (file: /// assets /) to load. You can also call a javaScrpit method.

  • loadData(String data, String mimeType, String encoding)

  • loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)

    Load some html code

  • reload()

    Refresh the current page

  • getTitle()

    Gets the title of the current page

  • canGoBack()

  • goBack()

    Determine whether webview able to return to the previous step

5. Note the use of WebView

1, in android 4.2 version of the phone has a problem that, webview JavaScript is injected, resulting in information security issues arise phones, such as downloading a virus, send text messages and so on. The problem lies in addJavascriptInterface method. JavaScript can be operated directly by calling the native JAVA interface to this interface.

2, google in version 4.2 of the above solves this problem, the solution is to add a statement in the above method is called js, @JavascriptInterface, But the 4.2 version of the phone there is no official proposed solutions. For now the 4.2 version of the phone can employ several methods to solve the security problem :

  • 1 custom url communicate, we can rewrite the received parameter method shouldOverrideUrlLoading
  • 2 by passing parameters through js prompt method onJsPrompt

four,Five ways to interact with HTML5 and Java

  • 1 onJsAlert->JavaScript->alter
  • 2 onJsPrompt -> JavaScript-> prompt-> java returns a parameter to js
  • 3 onJsConfirm -> JavaScript-> Confirm-> java returns a parameter to js
  • 4 addJavascriptInterface -> (Since this method is easy to trigger injection, we introduce notes, only suitable for 4.2+) -> @ JavascriptInterface
  • Jump url. 5 -> shouldOverrideUrlLoading-> treated (4.2 or lower adaptation) The url

Guess you like

Origin blog.csdn.net/MaybeForever/article/details/96431439