Android WebView Development Tutorials

Source: Internet
Author: User
Tags call back string find

Use of 1.WebView

(a). Create an instance of WebView to join the activity

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

or configure WebView in XML

<webview      android:layout_width= "match_parent"      android:layout_height= "match_parent" >  </ Webview>  

(b). Visit the Web page

Webview.loadurl ("https://www.baidu.com/");  
2.WebView API Usage (a). 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

Attention:

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".

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 Note: All resources on the page are Reloaded

public void stoploading ()  

Stop loading page

(b). Forward and backward pages
public void GoBack ()  //page back public void GoForward ()  //page forward public void Gobackorforward (int steps)//with current index Forward or back to the steps specified in the history, or  backward if steps is negative, positive for forward public boolean cangoforward ()  //To determine if the page can advance public boolean CanGoBack ()  //Determine if the page can be back
(c). JavaScript Operations
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.

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

Link: Android WebView summary--java and JavaScript interaction

Link: JS vulnerability exists with WebView component Addjavascriptinterface method under Android 4.2 version

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

Note: 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.

(d). Web search Function
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

(E). WebView Event Callback Listener
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.webviewclient,webchromeclient

WebView as a vector control that hosts Web pages, he generates events during the Web page display and callbacks to our application so that we can do what the application wants to do during the page loading process. For example, the client needs to display the Web page loading progress, page loading errors and so on events. WebView provides two event callback classes to the application layer, respectively, for webviewclient,webchromeclient developers to inherit these two classes and take over the corresponding event handling. Webviewclient mainly provides the Web page loading various stages of the notification, such as Web page start loading onpagestarted, page end loading onpagefinished, etc. webchromeclient mainly provide the content of the data provided during the Web page loading, For example, return to the title of the page.

(a). Webviewclient

--webviewclient use

Create the Webviewclient instance and set it to the WebView object, with the following code reference:
Webview.setwebviewclient (New Webviewclient () {@Override public      void onpagestarted (webview view, String URL, Bitmap Favicon) {         //Todo      }        @Override public      void onpagefinished (WebView view, String URL) {        //Todo      }  });  

-- Webviewclient API Detailed

public boolean shouldoverrideurlloading (WebView view, String URL)  
When the loaded Web page needs to redirect, it will call back this function tells us whether the application needs to take over the control page load, if the application takes over, and return true means that the program takes over the page load, if return false let WebView handle it by itself. Note: (1) This callback is not notified when the request is in the "POST" mode. (2) When the address we visit needs to be handled by our application, we can intercept it here, for example, if we find a link to a market, we can go directly to the marketplace, or to other apps.
public void onpagestarted (WebView view, String URL, Bitmap favicon)  
When you start loading the URL of the access, the application is notified that the function for each main frame is called only once, the page contains an IFRAME, or framesets does not call another onpagestarted, when the frame inside the page is embedded Onpagestarted is not called when a change occurs. Note: When we reload a URL by Loadurl, we call onpagestarted again and call Shouldoverrideurlloading, when we click on a link in the open URL, This will call Shouldoverrideurlloading before calling onpagestarted. However, shouldoverrideurlloading is not necessarily called every time, but only when it is needed.
public void onpagefinished (WebView view, String URL)  
When the current page is loaded, our application is notified, and the function is called only in the case of main frame.
public void Onloadresource (WebView view, String URL)  

Notifies the application that WebView is about to load URL-developed resources
Public Webresourceresponse shouldinterceptrequest (WebView view, String URL)  

Notifies the application that the kernel is about to load URL-developed resources, the application can return local resources to the kernel, and if the returned data is processed locally, the kernel does not fetch data from the network.

Note: This callback is not necessarily performed on the UI thread, so we need to be aware of the actions associated with view or private data here. If we need to change the background of the page, or need to implement the page color customization needs, can be processed at this callback time.
public void Onreceivederror (WebView view, int errorCode,  string description, String failingurl)
When a browser accesses a URL that has been made, it notifies us of the application, such as a network error.
Parameter description: @param view to receive the instance of Webviewclient, see Webview.setwebviewclient (New Myandroidwebviewclient ()) above, that is the webview. @param errorCode Error number can find the corresponding error name in the webviewclient.error_*. @param description describes the wrong information @param failingurl the URL of the current access failure, note that it is not necessarily our main URL note: In Onreceiveerror we can customize the page's error page.
public void Onformresubmission (WebView view, message dontresend, message resend)  

If the browser needs to resend the POST request, it can be handled by this time. The default is to not resend the data.
public void Doupdatevisitedhistory (WebView view, String URL, boolean isreload)  
The notification application can store the current URL in the database, meaning that the current access URL is in effect and is logged in the kernel. This function is only called once during page loading. Note that the page forward and backward does not callback this function.
public void Onreceivedhttpauthrequest (WebView view, Httpauthhandler handler, string host, String realm)  
Notifies the application that WebView receives an HTTP AUTH request, and the application can use supplied to set the WebView response request. The default behavior is to cancel this request.
public boolean shouldoverridekeyevent (WebView view, KeyEvent event)   

Provides application synchronization an opportunity to handle key events, menu shortcuts need to be filtered out. If return True,webview does not handle the event, WebView will always handle the event if it returns false, so there is no parent class on the view chain that can respond to this event. The default behavior is return false;

public void onscalechanged (WebView view, float Oldscale, float newscale)  
Notifies the application that WebView is to be scale. Applications can handle change events, such as adjusting the adaptation screen. (b). Webchromeclient

--webchromeclient use

Webview.setwebchromeclient (New Webchromeclient () {});
--webchromecilent API DetailedCreate the Webchromeclient instance and set it to the WebView object, with the following code reference:
public void onprogresschanged (WebView view, int newprogress)  
Notifies the application of the current page load progress.
public void Onreceivedtitle (WebView view, String title)  
When the title of document changes, the application is notified. Note: This function call timing is not certain, it may be very early, it may be late, depending on the page put the title location, most of the page generally put the title to the front of the page, so a lot of things will be early callback to this function.
public void Onreceivedicon (WebView view, Bitmap icon)  
This function is recalled when the current page has a new favicon.
public void Onshowcustomview (view view, Customviewcallback callback)  

Notifies the application that WebView needs to display a custom view, which is primarily used in the video full screen html5video support.

Parameter description: @param view is about to display the View@param callback when view needs dismiss use this object for callback notification.
public void Onhidecustomview ()  
Exit Video Notifications
public boolean Oncreatewindow (WebView view, Boolean Isdialog, Boolean isusergesture, Message resultmsg)  
Request to create a new window, if our application takes over this request, must return true, and create a new WebView to host the main window. If the application does not process, you need to return FALSE, and the default behavior is the same as returning false. Parameter description: Webview@param isusergesture for creating a new window @param view request If true, the description is from the user to clean up the operation behavior, such as the user click the link @param isdialog true The new window created by the request must be a dialog, not a full-screen window. @param resultmsg A message needs to be sent when WebView is created. WebView.WebViewTransport.setWebView (WebView)
public void Onrequestfocus (WebView view)
WebView request to get focus, this is mainly the current webview is not the foreground state, is the background webview.
public void Onclosewindow (WebView window)  
Notifies the application to remove the WebView passed over from the view tree.
public boolean Onjsalert (WebView view, string URL, string message, jsresult result)  

Notifies the application that the JavaScript Alert dialog box is displayed, and if the application returns True the kernel considers the application to handle this message, returning false to the kernel itself.

Note: If we apply takeover processing, we must give results of result, result.cancel,result.comfirm must call it, otherwise the kernel will hang.
public boolean onjsconfirm (WebView view, string URL, String message,  jsresult result)  
Notifies the application that the Confirm dialog box is available. Parameter Description ditto Onjsalert
public boolean onjsbeforeunload (WebView view, string URL, String message,  jsresult result)  
The notification application displays a dialog box that lets the user choose whether to leave the current page, which is the onbeforeunload event in JavaScript, and if the client returns true, the kernel considers the client to provide a dialog box. The default behavior is return FALSE. The parameter description is the same as the Onjsalert () described earlier.
public void Openfilechooser (valuecallback<uri> uploadfile, String accepttype, string capture)  
This callback is a private callback, when the page needs to request to open the system's file selector, it will be called back to this method, such as we need to upload images, request photos, mail attachments upload and so on. If you do not implement this private API, none of the above requests will be executed. 4.WebSettingsAndroid WebView provides display Web pages, as well as some customization of our application to page loading, such as the fact that we can set the currently loaded page to not display images in order to reduce network data. Android provides some setting class websettings for managing WebView, and WebSettings objects are created when the WebView object is created, with the default settings values attached. WebSettings objects can be obtained by webview.getsettings (). The life cycle of the websettings is the same as the WebView life cycle, and if WebView is destroy then WebSettings should be released, otherwise if you use websettings to continue the operation, Throws an exception illegalstateexception. Note: All functions that call websettings settings are made asynchronously, so we cannot set a state to take effect immediately. (a). WebSettings API Detailed
Public synchronized void Setloadsimagesautomatically (Boolean flag)  

Sets whether the current WebView needs to load the picture, which controls the state of the entire webview and takes this strategy for all resources. If set to false then access the current URL so that the picture resource will not be loaded. The default value is True , and by configuring the flag of this method, you can implement the browser's non-graph mode and the control of the graph mode.

Public synchronized void Setblocknetworkimage (Boolean flag)  
This method is valid when Getloadsimagesautomatically returns TRUE, the default value is: false;
public void Setcachemode (int mode)  
A normal web page loading cache will be checked, the content will be re-verified, the first time you visit a Web page, the cache will be stored locally, setting policy can make the page load mode changes, the cache mode is as follows: Load_default: If our application does not set any Cachemode, this is the default cache mode. Loading a Web page checks to see if there is a cache, and if it does, use the local cache if it does not expire, or get it from the network. Load_cache_else_network: Use the cache resource, even if it expires, if it is not available from the network without the cache. Load_no_cache: Get load_cache_only from the network without using the cache: use only the content on the cache.

Normal: Normally displayed, no rendering changes.
Single_column: Put everything in a wide column such as the WebView component. This is mandatory, the Web page has been squeezed (basically not recommended)
Narrow_columns: If possible, the width of all columns does not exceed the width of the screen. The default
Text_autosizing: This can be used in API 19 and beyond, and is not currently required to be understood and used.

public void Setloadwithoverviewmode (Boolean overview)  
The setting of the overview mode, which defaults to false.
Public synchronized void setjavascriptenabled (Boolean flag)  
The default value is False.  If we need JavaScript on our web page, we need to turn on this setting, otherwise the page will not load completely. 5. WebView using TIPS (a). Custom error display interface for WebView:

Overwrite the Onreceivederror () method in Webviewclient:

/** * Displays the custom error prompt page, with a view overlay in WebView */protected void Showerrorpage () {LinearLayout Webparentview = (linearlayout            ) mwebview.getparent ();      Initerrorpage ();      while (Webparentview.getchildcount () > 1) {webparentview.removeviewat (0);      } linearlayout.layoutparams LP = new Linearlayout.layoutparams (layoutparams.fill_parent,layoutparams.fill_parent);      Webparentview.addview (Merrorview, 0, LP);  Miserrorpage = true;            } protected void Hideerrorpage () {LinearLayout Webparentview = (linearlayout) mwebview.getparent ();      Miserrorpage = false;      while (Webparentview.getchildcount () > 1) {webparentview.removeviewat (0); }} protected void Initerrorpage () {if (Merrorview = = null) {Merrorview = View.inflate (This, r.la          Yout.online_error, NULL);          Button button = (button) Merrorview.findviewbyid (r.id.online_error_btn_retry);       Button.setonclicklistener (New Onclicklistener () {       public void OnClick (View v) {mwebview.reload ();          }          });      Merrorview.setonclicklistener (NULL); }} @Override public void Onreceivederror (WebView view, int errorCode, string description, String failingurl) {MEr    Rorview.setvisibility (view.visible);  Super.onreceivederror (view, ErrorCode, description, Failingurl); }          =
(b). WebView Cookies Cleanup
Cookiesyncmanager.createinstance (this);   Cookiesyncmanager.getinstance (). Startsync ();   Cookiemanager.getinstance (). Removesessioncookie ();   
(c). Clean up cache and history
Webview.clearcache (true);   Webview.clearhistory ();  
(d). Shielding Long Press events
Mwebview.setonlongclicklistener (New Onlongclicklistener () {                        @Override public            boolean Onlongclick (View v) {                return true;            }  });  
(E). WebView retains the zoom function, but hides the zoom control price
Mwebview.getsettings (). Setsupportzoom (true);  Mwebview.getsettings (). Setbuiltinzoomcontrols (true);  if (Deviceutils.hashoneycomb ()) {mwebview.getsettings (). Setdisplayzoomcontrols (false);  
}
Note: Setdisplayzoomcontrols is the new API in Android 3.0.

Android WebView Development Tutorials

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.