Android WebView Development Details (i)

Source: Internet
Author: User
Tags string find

Overview:

Android WebView is a special view on the Android platform that can be used to display Web pages, which can be used to display only an online page in your app and to develop a browser. WebView internal implementation is the use of the rendering engine to display the content of the view, providing Web page forward and backward, Web page zoom in, zoom out, search, front-end developers can use the Web Inspector (Android 4.4 system support, 4.4 can use http:// developer.android.com/guide/webapps/debugging.html) debugging Html,css,javascript and so on. With the Android 4.3 system and its webview internal WebKit rendering engine, the Android 4.4 uses the chromium rendering engine to render the contents of the view.

Basic use of 1.WebView

(1) Create an instance of WebView to join the Activity view tree

WebView WebView = new WebView (this); Setcontentview (WebView);

(2) Configuring WebView in XML

    <webview        android:layout_width= "match_parent"        android:layout_height= "match_parent" >    </ Webview>
(3) Access to Web pages

Webview.loadurl ("http://developer.android.com/");

2.WebView API using detailed 1) request to load a webpage section
public void LoadData (string data, String MimeType, String encoding)

Load the specified data

Parameter description:

Data strings in string form can be encoded by base64

Minetype the MIME type of data, e.g. ' text/html '

Encoding Data encoding format

Tips:

1.Javascript has a homologous limitation, and the same-origin policy restricts the way in which a source is loaded or the script interacts with data from other sources. To avoid this limitation, you can use the Loaddatawithbaseurl () method.

The 2.encoding parameter is set to whether the data parameter is base64 or URL encoded, and if data is Base64 encoded then encoding must fill in "base64".

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

public void Loaddatawithbaseurl (string baseUrl, String data, String MimeType, String encoding, String historyurl)
Using BaseURL to load the Web page content of the base URL, BaseURL addresses the same source problem using JavaScript for the relevant URL.

public void Loadurl (String URL)
Load Web page content that develops URLs

public void Loadurl (String url, map<string, string> additionalhttpheaders)

Loads the development URL and carries the HTTP header data.

public void Reload ()

Reload page

Tip (important)

Page All resources are reloaded

public void stoploading ()


2) Forward and backward

public void GoBack ()
public void GoForward ()
public void Gobackorforward (int steps)
Forward with the current index as the starting point or back to the steps specified in the history, or backward if the steps is negative, and the positive as the forward

public boolean CanGoForward ()
public boolean cangoback ()


3) JavaScript operation

public void Addjavascriptinterface (Object object, String name)

When a Web page needs to interact with the app, you can inject Java objects into the JAVASCRITP call. Java objects provide the appropriate method for JS to use.

Tips (important)

Problem: Using this API under Android 4.2 involves JavaScript security issues, and JavaScript can attack by reflecting the related classes of this Java object.

Workaround: This method can be called using the white list mechanism.

In Android4.2 more than the system needs to provide JS call method before adding a gaze: @JavaScriptInterface; In the virtual machine, JavaScript calls the Java method to detect the anotation, and if the method is identified @javascriptinterface JavaScript can successfully invoke the Java method, otherwise the call is unsuccessful.

Example

Class Jsobject {    @JavascriptInterface public    String toString () {return "Injectedobject";}} Webview.addjavascriptinterface (New Jsobject (), "Injectedobject");

public void Evaluatejavascript (String script, valuecallback<string> resultcallback)
This method is introduced in the Android 4.4 system and is therefore only available in the Android4.4 system, providing asynchronous execution of JavaScript code in the context of the current page display

Tips (important)

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

So how do you execute Javascrit code in Android4.4?

The Loadurl method that can be provided by WebView: the specific format is as follows:

Webview.loadurl ("Javascript:alert (injectedobject.tostring ())");

Where javascript: is the identifier for executing JavaScript code, followed by a JavaScript statement.

public void Removejavascriptinterface (String name)
Java object injected to WebView when Addjavascripinterface is deleted. This method WebView on different Android systems and there will be a failure condition.

4) Web search function

public int FindAll (String find)
This API has been removed on Android 4.1, and the Findallasync method is used on Android 4.1 extreme systems

This API also has bugs specific please see my previous blog post on Android WebView FindAll bug

public void Findallasync (String find)
Asynchronously executes a search for characters contained within a Web page and sets highlighting, and the lookup results are recalled.

public void FindNext (Boolean forward)
Finds the next matching character

Using Example:

public class Testfindlistener implements Android.webkit.WebView.FindListener {    private findlistener Mfindlistener ;    Public Testfindlistener (Findlistener findlistener) {        mfindlistener = Findlistener;    }    @Override public    void onfindresultreceived (int activematchordinal, int numberofmatches,            boolean isdonecounting) {        mfindlistener.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 post on Android WebView API findAll bug        }    }        Mwebview.findnext (forward);

5) Data Removal section

public void ClearCache (Boolean includediskfiles)
Clears the cache left by Web page access because the kernel cache is global, so this approach is not just for webview but for the entire application.

public void Clearformdata ()
This API simply clears the AutoComplete-filled form data and does not erase the data that WebView stores locally.

public void ClearHistory ()
Clears the history of the current WebView access, only webview all records in the access history except the current access record.

public void Clearmatches ()
Clear highlighted match characters for web search

public void ClearView ()
This API is discarded on Android 4.3 and above, and this API is mostly bug-less and often does not erase previous rendering data. The official proposal through Loadurl ("About:blank") to achieve this function, rain need to reload a page natural time will be affected.

6) Status of the WebView

public void Onresume ()
Activates the webview as active, and can perform the response of the webpage normally

public void OnPause ()
When the page is lost focus is switched to the background invisible State, need to perform onpause, OnPause action notifies the kernel to suspend all actions, such as DOM parsing, plugin execution, JavaScript execution. And can reduce unnecessary CPU and network overhead, can achieve save electricity, save traffic, save the effect of resources.

public void Pausetimers ()

When the application is switched to the background we use WebView, which is not only for the current webview but for the global full application WebView, which pauses all webview layout,parsing,javascripttimer. Reduce CPU power consumption.

public void Resumetimers ()
The action when restoring pausetimers.

public void Destroy ()
Tips (important)

This method must be removed from the view tree before it can be executed, which notifies native to release all resources that the webview occupies. WebView

7) WebView Event callback Monitor

public void Setwebchromeclient (Webchromeclient client)
Mainly notifies the client app to load events such as Title,favicon,progress,javascript dialog of the current webpage, notifying the client to handle these corresponding events.

public void Setwebviewclient (Webviewclient client)
The main notification client app loads the current page when the various timing states, onpagestart,onpagefinish,onreceiveerror and other events.


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/";p rivate 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 ();p rivateClass 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.onpa gestarted (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-gen Erated method Stubsuper.onreceivederror (view, ErrorCode, description, failingurl);} @Overridepublic void Doupdatevisitedhistory (WebView view, String Url,boolean isreload) {//TODO auto-generated method Stu Bsuper.doupdatevisitedhistory (view, URL, isreload);}} Private Webchromeclientbase mwebchromeclientbase = new Webchromeclientbase ();p rivate 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);}}}

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


Reprint please indicate the source http://blog.csdn.net/typename/article/details/39030091 powered by Meichal Zhao

Have a question welcome to the discussion














Android WebView Development Details (i)

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.