Android WebView development (1)

Source: Internet
Author: User
Tags string find

Android WebView development (1)
Overview:

Android WebView is a special View on the Android platform. It can be used to display webpages. This class can be used to display only one online webpage in your app, it can also be used to develop browsers. The internal implementation of WebView is to use a rendering engine to display the view content. It provides forward and backward web pages, webpage amplification, downsize, and search. Front-end developers can use web inspector (supported by Android 4.4, 4.4 you can use http://developer.android.com/guide/webapps/debugging.html) debugging HTML, CSS, Javascript and other functions. In Android 4.3 and Its WebView, the Webkit rendering engine is used internally. In Android 4.4, the chromium rendering engine is used to render the View content.

1. Basic use of WebView

(1) create a WebView instance and add it to the Activity view tree.

 

WebView webview = new WebView(this);setContentView(webview);

 

(2) Configure WebView in xml

 

    
     
 
(3) webpage access

 

 

webview.loadUrl(http://developer.android.com/);

2. WebView API Usage Details 1) Request to load the webpage Section
public void loadData (String data, String mimeType, String encoding)

 

Load specified data

Parameter description:

Data in String format can be encoded using base64.

MIME Type of mineType data, e.g. 'text/html'

Encoding format of encoding data

Tips:

1. Javascript has the same-source restriction. The same-source policy limits the ways in which a text or script is loaded in one source to interact with data from other sources. To avoid this restriction, you can use the loadDataWithBaseURL () method.

2. Set the encoding parameter to determine whether the data parameter is base64 or URL encoded. If the data is base64 encoded, encoding must be filled with base64 ".

Http://developer.android.com/reference/android/webkit/WebView.html

 

public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)
Use baseUrl to load the webpage content of the base URL. The baseUrl solves the problem that the url uses the same source of Javascript.

 

 

public void loadUrl (String url)
Load the url-based webpage content

 

 

public void loadUrl (String url, Map
 
   additionalHttpHeaders)
 

Load the specified url and carry the http header data.

 

public void reload ()

Reload the page

Tip (important)

All resources on the page are reloaded.

 

public void stopLoading ()

 

 

2) move forward and backward

 

public void goBack ()
public void goForward ()
public void goBackOrForward (int steps)
Start from the current index or return to the specified steps in the history. If steps is negative, it is backward, and positive is forward.

 

 

public boolean canGoForward ()
public boolean canGoBack ()

 

3) JavaScript operations

 

public void addJavascriptInterface (Object object, String name)

When the webpage needs to interact with the App, Java objects can be injected to call javascrui. Java objects provide corresponding methods for js to use.

 

Tips (important)

Problem: using this api below Android 4.2 involves JavaScript Security Issues. javascript can be attacked by reflecting the classes of this java object.

Solution: You can use the whitelist mechanism to call this method.

When Android4.2 is extremely high, the system needs to add a watch before providing js call Methods: @ JavaScriptInterface; In the virtual machine, Javascript calls the Java method to detect this anotation, if the method is identified as @ JavaScriptInterface, Javascript can successfully call this Java method. Otherwise, the call fails.

Example:

 

 class JsObject {    @JavascriptInterface    public String toString() { return injectedObject; } } webView.addJavascriptInterface(new JsObject(), injectedObject);

public void evaluateJavascript (String script, ValueCallback
 
   resultCallback)
 
This method is introduced in Android 4.4, so it can only be used in Android4.4 system. It provides asynchronous execution of javascript code in the current page display context.

 

Tips (important)

This method must be called in the UI thread, and the callback of this function will also be executed in the UI thread.

In Android4.4, how does one execute the javascrit code?

The loadUrl method provided by WebView is as follows:

 

webView.loadUrl(javascript:alert(injectedObject.toString()));

Javascript: indicates the execution of javascript code, followed by a javascript statement.

 

public void removeJavascriptInterface (String name)
Java object injected to webview when addJavascripInterface is deleted. This method may be faulty in WebView of different Android systems and may fail.

 

4) Webpage Search

 

public int findAll (String find)
This API has been removed in Android 4.1, and the findAllAsync method is used in Android 4.1 and later systems.

 

This API also has bugs. For details, see my previous blog post Android WebView findAll bug.

 

public void findAllAsync (String find)
Asynchronously searches for the characters contained in the webpage and sets the highlight. The search result is called back.

 

 

public void findNext (boolean forward)
Find the next matched character

 

Use example:

 

Public class TestFindListener implements android. webkit. webView. findListener {private FindListener mFindListener; public TestFindListener (FindListener findListener) {mFindListener = findListener;} @ Override public void listener (int listener, int listener, boolean isDoneCounting) {listener. onFindResultReceived (activeMatchOrdinal, numberOfMatches, isDoneCounting) ;}} Public void findAllAsync (String searchString) {if (android. OS. build. VERSION_CODES.JELLY_BEAN <= Build. VERSION. SDK_INT) mWebView. findAllAsync (searchString); else {int number = mWebView. findAll (searchString); if (mIKFindListener! = Null) mIKFindListener. onFindResultReceived (number); fixedFindAllHighLight (); // see my previous blog: Android WebView API findAll bug} mWebView. findNext (forward );

5) data cleanup

 

public void clearCache (boolean includeDiskFiles)
Clear the cache left by web access. Because the kernel cache is global, this method is not only for webview, but for the entire application.

 

 

public void clearFormData ()
This api only clears automatically filled form data, and does not clear the data stored locally by WebView.

 

 

public void clearHistory ()
Clear the access history of the current webview. Only the access history of the current webview is deleted.

 

 

public void clearMatches ()
Clear highlight matching characters for Webpage Search

 

 

public void clearView ()
In Android 4.3 and later systems, this api is discarded, and this api has bugs in most cases, and it often cannot clear the previous rendering data. The official recommendation is to use loadUrl (about: blank) to implement this function. It may take some time to reload a page.

 

6) WebView status

 

public void onResume ()
The WebView is activated and the webpage response can be executed normally.

 

 

public void onPause ()
When the page is switched to the invisible state in the background, the onPause action must be executed. The onPause action notifies the kernel to suspend all actions, such as DOM parsing, plugin execution, and JavaScript Execution. In addition, it can reduce unnecessary CPU and network overhead and save power, save traffic and save resources.

 

 

public void pauseTimers ()

When the application is switched to the backend, we use webview. This method is not only for the current webview, but for the global webview of the entire application. It will suspend layout, parsing, and javascripttimer of all webviews. Reduce CPU power consumption.

 

 

public void resumeTimers ()
Restore pauseTimers.

 

 

public void destroy ()
Tips (important)

 

This method can only be executed after the webview is deleted from the view tree. This method notifies native to release all resources occupied by webview.

7) WebView Event Callback listener

 

public void setWebChromeClient (WebChromeClient client)
It mainly notifies the client app to load the title, Favicon, progress, javascript dialog and other events of the current webpage, and notifies the client to process these events.

 

 

public void setWebViewClient (WebViewClient client)
It mainly notifies the client app of various timing states, such as onPageStart, onPageFinish, and onReceiveError when loading the current webpage.

 

 

3. WebView Demo
package com.example.webviewdemo;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.os.Message;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;public class WebViewBase extends WebView {private static final String DEFAULT_URL = http://www.ijinshan.com/;private Activity mActivity;public WebViewBase(Context context) {super(context);mActivity = (Activity) context;init(context);}@SuppressLint(SetJavaScriptEnabled)private void init(Context context) {WebSettings webSettings = this.getSettings();webSettings.setJavaScriptEnabled(true);webSettings.setSupportZoom(true);//webSettings.setUseWideViewPort(true);this.setWebViewClient(mWebViewClientBase);this.setWebChromeClient(mWebChromeClientBase);this.loadUrl(DEFAULT_URL);this.onResume();}private WebViewClientBase mWebViewClientBase = new WebViewClientBase();private class WebViewClientBase extends WebViewClient {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// TODO Auto-generated method stubreturn super.shouldOverrideUrlLoading(view, url);}@Overridepublic void onPageStarted(WebView view, String url, Bitmap favicon) {// TODO Auto-generated method stubsuper.onPageStarted(view, url, favicon);}@Overridepublic void onPageFinished(WebView view, String url) {// TODO Auto-generated method stubsuper.onPageFinished(view, url);}@Overridepublic void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {// TODO Auto-generated method stubsuper.onReceivedError(view, errorCode, description, failingUrl);}@Overridepublic void doUpdateVisitedHistory(WebView view, String url,boolean isReload) {// TODO Auto-generated method stubsuper.doUpdateVisitedHistory(view, url, isReload);}}private WebChromeClientBase mWebChromeClientBase = new WebChromeClientBase();private class WebChromeClientBase extends WebChromeClient {@Overridepublic void onProgressChanged(WebView view, int newProgress) {mActivity.setProgress(newProgress * 1000);}@Overridepublic void onReceivedTitle(WebView view, String title) {// TODO Auto-generated method stubsuper.onReceivedTitle(view, title);}@Overridepublic void onReceivedTouchIconUrl(WebView view, String url,boolean precomposed) {// TODO Auto-generated method stubsuper.onReceivedTouchIconUrl(view, url, precomposed);}@Overridepublic boolean onCreateWindow(WebView view, boolean isDialog,boolean isUserGesture, Message resultMsg) {// TODO Auto-generated method stubreturn super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);}}}

 

 

 




 





 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.