Android WebView development details

Source: Internet
Author: User

Android WebView development details

Android WebView development details

1. Overview:
Android WebView is a carrier control that carries web pages. It generates some events and calls back the events to our applications, so that we can do what the application wants to handle during webpage loading. For example, the client needs to display the webpage loading progress, webpage loading errors, and other events. WebView provides two Event Callback classes to the application layer, WebViewClient. WebChromeClient developers can inherit these two classes and take over the corresponding event processing. WebViewClient mainly provides notifications for various stages of webpage loading, such as loading onPageStarted from a webpage and loading onPageFinished from the webpage. WebChromeClient mainly provides the data content provided during webpage loading, such as the returned webpage title, favicon.

2. Basic use of WebViewClient:
Create a WebViewClient instance and set it to a WebView object. The specific code is as follows:

class MyAndroidWebViewClient extends WebViewClient {       @Override      public void onPageStarted(WebView view, String url, Bitmap favicon) {         // TODO      }      @Override      public void onPageFinished(WebView view, String url)      {        // TODO      }   }  webview.setWebViewClient(new MyAndroidWebViewClient ());  

3. WebViewClient API details:
1) webpage loading time part:

public boolean shouldOverrideUrlLoading(WebView view, String url)  

When the webpage to be loaded needs to be redirected, the function will be called back to inform us whether the application needs to take over and control webpage loading. If the application takes over and returns true, it means that the main program takes over webpage loading, if false is returned, let webview handle it by itself.

Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url: the url to be loaded
@ Return true the current application needs to process the url by itself, and false is returned without processing.
Tips
(1) This callback will not be notified when the request method is "POST.
(2) When the address we access needs to be handled by our application, we can intercept it here. For example, we find that the link to the market is a link, then we can directly jump to the application market or other apps.

public void onPageStarted(WebView view, String url, Bitmap favicon)  

When the kernel starts to load the access url, the application will be notified. This function will only be called once for each main frame. The page contains iframe or framesets and will not call onPageStarted again, onPageStarted is not called when the embedded frame in the webpage changes.

Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url: the url to be loaded
@ Param favicon if the favicon has been stored in the local database, the favicon of the web page is returned; otherwise, the return value is null.

Tips:
(1) iframe may be something that many people do not know. Here I will explain how to load iframe. There are many links below. We can click a link that is an iframe of the current host.
(2) The developer may be confused. Which of the two functions of onPageStarted and shouldOverrideUrlLoading are called first during webpage loading.
When we reload a URL using loadUrl, onPageStarted will be called before shouldOverrideUrlLoading. When we click a link in the URL, in this case, shouldOverrideUrlLoading is called before onPageStarted. However, shouldOverrideUrlLoading is not always called every time. It is called only when necessary.

  public void onPageFinished(WebView view, String url)  

When the kernel loads the current page, it will notify our application. This function will be called only when the main frame is used. After this function is called, The rendered image will not be updated, to receive notifications of new images, use @ link WebView. pictureListener # onNewPicture.

Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url: the url to be loaded

public WebResourceResponse shouldInterceptRequest(WebView view,              String url)  

Notify the application kernel that the resources specified by the url will be loaded. The application can return local resources and provide them to the kernel. If local processing returns data, the kernel will not obtain data from the network.

Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url raw url Resources
@ Return returns WebResourceResponse containing data objects, or returns null

Tips
This callback is not necessarily executed in the UI thread, so we need to note the View or private data-related actions here.
If we need to change the background of the webpage or customize the color of the webpage page, we can handle it at this callback time.

public void onReceivedError(WebView view, int errorCode,              String description, String failingUrl) 

When an error occurs when the browser accesses the specified website, the application will be notified, such as a network error.

Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param errorCode the ERROR code can be found in WebViewClient. ERROR.
@ Param description indicates the error message.
@ Param failingUrl the url of the current access failure. Note that it is not necessarily our main url

Tips
In onReceiveError, We can customize the webpage error page.

public void onFormResubmission(WebView view, Message dontResend,              Message resend)  

If the browser needs to resend the POST request, you can handle it at this time. Data is not resend by default.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param dontResent this parameter can be used when the browser does not need to resend data.
@ Param resent this parameter can be used when the browser needs to resend the data.

public void doUpdateVisitedHistory(WebView view, String url,              boolean isReload)  

The notification application can store the current url in the database, which means that the current access url has taken effect and is recorded in the kernel. This function is called only once during webpage loading. Note that this function is not called back when the webpage moves forward and backward.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url the url currently being accessed
@ Param isReload: if it is true, the url is being reloaded.

public void onReceivedSslError(WebView view, SslErrorHandler handler,              SslError error)  

This method is called when an SSL error is found during web page resource loading. Our application must make a response, whether to cancel the handler. cancel () request or continue to request handler. proceed (); the default behavior of the kernel is handler. cancel ();

Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param handler: the object that processes the user request.
@ Param error SSL error object

Tips
The kernel will remember this selection. If the same error persists next time, the kernel will directly execute the selected result.

public void onReceivedHttpAuthRequest(WebView view,              HttpAuthHandler handler, String host, String realm) 

The notification application WebView receives an Http auth request. The application can use supplied to set the webview Response Request. The default behavior is cancel.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param handler: the object used to respond to the WebView request
@ Param host: The authenticated host
@ Param realm seriously requests the domain

public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event)   

Provides an opportunity for the application to synchronize a key event, and the menu shortcut key needs to be filtered out. If true is returned, webview does not process this event. If false is returned, webview will always process this event. Therefore, no parent class on the view chain can respond to this event. The default behavior is return false;
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param event keyboard event name
@ Return if true is returned, the application processes the time, and false is returned for webview processing.

public void onScaleChanged(WebView view, float oldScale, float newScale)  

Notify the application webview to be scaled. Applications can handle changes, such as adjusting the adaptation screen.

public void onReceivedLoginRequest(WebView view, String realm,              String account, String args)  

Notifies the application of an Automatic Logon account process.
Parameter description:
@ Param view the webview requested for login
@ Param realm the domain name of the account, used to find the account.
@ Param account: an optional account. If it is null, check with the local account. If it is an available account, logon is provided.
@ Param args verify the login user who has set parameters

5. WebChromeClient API details
Create a WebChromeClient instance and set it to a WebView object. The specific code is as follows:

public void onProgressChanged(WebView view, int newProgress)  

Notifies the application of the current webpage loading progress.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.

public void onReceivedTitle(WebView view, String title)  

When the title of the document changes, the application will be notified.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param title document New title
Tips
The call time of this function is unknown. It may be very early or very late. It depends on the location where the title is set on the webpage. Most webpages usually set the title to the front of the page, therefore, in many cases, this function will be adjusted back early.

public void onReceivedIcon(WebView view, Bitmap icon)  

When the current page has a new favicon, this function is called back.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param icon favicon on the current page

public void onReceivedTouchIconUrl(WebView view, String url,              boolean precomposed)  

Url of the notification application apple-touch-icon
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url the server address of apple-touch-icon
@ Param precomposed if precomposed is true, touch-icon is created in advance.
Tips
If the application needs this icon, you can obtain the icon through this url.

public void onShowCustomView(View view, CustomViewCallback callback)  

The webview of the notification application needs to display a custom view, which is mainly used for full screen video HTML5Video support.
Parameter description:
@ Param view the view to be displayed
@ Param callback: This object is used for callback notifications when the view requires dismiss.

public void onHideCustomView()  

Exit video notification

public boolean onCreateWindow(WebView view, boolean isDialog,              boolean isUserGesture, Message resultMsg)  

Request to create a new window. If our application takes over this request, true must be returned and a new webview is created to hold the main window.
If the application is not processed, false is returned. The default behavior is the same as false.
Parameter description:
@ Param view: request to create the webview of the new window
@ Param isUserGesture if it is true, it indicates that it is from the user to clean up the operation, for example, the user clicks the link
@ Param isDialog true the new window to be created must be a dialog, rather than a full screen window.
@ Param resultMsg send a message when creating a webview. WebView. WebViewTransport. setWebView (WebView)
An example of Tips is as follows:

 private void createWindow(final Message msg) {  WebView.WebViewTransport transport = (WebView.WebViewTransport) msg.obj;  final Tab newTab = mWebViewController.openTab(null, Tab.this, true,          true);  transport.setWebView(newTab.getWebView());  msg.sendToTarget();    }  
public void onRequestFocus(WebView view)  

The webview request gets the focus. This occurs mainly because the current webview is not in the foreground status, but in the background webview.

public void onCloseWindow(WebView window)  

Notify the application to disable the passed webview and remove it from the view tree.

public boolean onJsAlert(WebView view, String url, String message,              JsResult result)  

Notify the application to display the javascript alert dialog box. If the application returns true, the kernel considers the application to process the message, returns false, and processes the message by itself.
Parameter description:
@ Param view: the instance that receives the WebViewClient. The preceding example shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview.
@ Param url the url loaded by webview In the javascript dialog box that appears in the current request.
@ Param message the pop-up content
@ Result is used to respond to user processing.

Tips
If our application takes over the processing, the result must be given. result. cancel and result. comfirm must be called later. Otherwise, the kernel will be hang.

public boolean onJsConfirm(WebView view, String url, String message,              JsResult result)  

The notification application provides the confirm dialog box.
Parameter description: Same as onJsAlert

public boolean onJsPrompt(WebView view, String url, String message,              String defaultValue, JsPromptResult result)  

The notification application displays a prompt dialog box.
Tips
The result. confirm method must be called if the application takes over this method.

public boolean onJsBeforeUnload(WebView view, String url, String message,              JsResult result)  

Notify the application to display a dialog box asking the user to choose whether to leave the current page. This callback is an onbeforeunload event in javascript. 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 onJsAlert.

public void onExceededDatabaseQuota(String url, String databaseIdentifier,              long quota, long estimatedDatabaseSize, long totalQuota,              WebStorage.QuotaUpdater quotaUpdater)  

Notifies the application webview kernel that the web SQL database has exceeded the quota and requests whether to increase the database disk quota. By default, the database quota is not increased.
Parameter description:

@ Param url: url address that triggers the database quota
@ Param databaseIdentifier indicates that the database quota is exceeded.
@ Param quota size of the original database quota, in bytes
@ Param estimatedDatabaseSize the data size that reaches the bottom line bytes
@ Param totalQuota Total Database quota size bytes
@ Param quotaUpdater: Specifies the object for updating the database quota. You can use quotaUpdater. updateQuota (newQuota) to configure the new database quota.

public void onReachedMaxAppCacheSize(long requiredStorage, long quota,              WebStorage.QuotaUpdater quotaUpdater)  

Notifies the application that the kernel has reached the maximum appcache.
Appcache is a HTML5 data processing standard for offline.

public void onGeolocationPermissionsShowPrompt(String origin,              GeolocationPermissions.Callback callback)  

Whether the current page request allows positioning.

Use of GeolocationPermissions. Callback

Public void invoke (String origin, boolean allow, boolean retain );

Parameter description:
@ Param origin the source address set for the permission
@ Param allow: whether to allow location
@ Retain whether to keep the kernel in mind for the current selection.

public void onGeolocationPermissionsHidePrompt()  
public void openFileChooser(ValueCallback
  
    uploadFile, String acceptType, String capture)  
  

This callback is a private callback. When the page needs to request to open the system's file selector, this method will be called back, such as uploading images, requesting photos, and uploading attachments to emails.
If this private API is not implemented, none of the above requests will be executed.

If you have any questions, please discuss them.

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.