Android WebView Development (2)

Source: Internet
Author: User

Android WebView Development (2)
Reprinted please indicate the source http://blog.csdn.net/typename/article/details/39495409 powered by meichal zhao
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.

1. Basic use of WebViewClient to 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 ());

2. WebViewClient API explanation 1) webpage loading time Section
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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url: the url to be loaded @ return true the current application needs to process the url by itself. If false is returned, no processing is performed.
Tips (1) when the request method is "POST", this callback will not be notified. (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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url: the url to be loaded @ param favicon if the favicon is already stored in the local database, the favicon of the webpage is returned; otherwise, the returned result is null.
Tips: (1) iframe may not be understood by many people. Here I will explain how iframe is loaded and there are many links below, you 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url: the url to be loaded
public void onLoadResource(WebView view, String url)
Notifies the application WebView that the resources specified by the url will be loaded soon.
Parameter description: @ param view refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url: url resource 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url the raw url specifies the resource. @ return returns the WebResourceResponse containing the data object, or returns null.
The Tips callback is not necessarily executed in the UI thread, so we need to pay attention to 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param errorCode the ERROR code can be found in WebViewClient. ERROR. @ Param description the error message @ param failingUrl the url of the failed access. 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url the url currently being accessed @ param isReload if it is true, this is the url 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param handler: the object that processes the user request. @ Param error SSL error object
The Tips 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param handler the object used to respond to the WebView request @ param host request authentication 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 refers to the instance that receives WebViewClient. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of this parameter, 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)

The notification application has an Automatic Logon account process parameter description: @ param view the Domain Name of the webview @ param realm account requested to log on, 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
3. basic use of WebChromeClient
4. The WebChromeClient API details how to 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance.
public void onReceivedTitle(WebView view, String title)

When the title of the document changes, the application parameter description will be notified: @ param view receives the instance of WebViewClient. The preceding figure shows webView. setWebViewClient (new MyAndroidWebViewClient (), which is the webview. @ Param title document the new titleTips function call time is unknown, may be very early, may be very late, depends on the position of the page to set the title, most Web pages usually set the title to the front of the page. Therefore, in many cases, the title will be adjusted back to this function.
public void onReceivedIcon(WebView view, Bitmap icon)

When the current page has a new favicon, this function is called back.
Parameter description: @ param view refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ 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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance. @ Param url: server address of apple-touch-icon @ param precomposed if precomposed is true, touch-icon is a pre-created Tips. If the application requires this icon, you can get 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: view @ param callback to be displayed. When the view requires dismiss, this object is used for callback notification.

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 a webview @ param isUserGesture in the new window. If it is true, it indicates that the operation is performed by the user, for example, if you click the link @ param isDialog true, the new window created by the request must be a dialog, rather than a full screen window. @ Param resultMsg send a message when creating a webview. The following is an example of WebView. WebViewTransport. setWebView (WebView) Tips:
    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 refers to the instance where the WebViewClient is received. webView. setWebViewClient (new MyAndroidWebViewClient () is displayed in front of the instance.
@ 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 must call the result. confirm method 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: the url address that triggers the database quota @ param databaseIdentifier indicates that the database quota is exceeded. @ Param quota the size of the original database quota, which is the bytes unit bytes @ param estimatedDatabaseSize that reaches the bottom line data size bytes @ param totalQuota Total Database quota size bytes @ param quotaUpdater updates the database quota object, you can use quotaUpdater. updateQuota (newQuota); 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 indicates the source address of the permission setting. @ param allow indicates whether to allow @ retain to locate whether the current selection should be remembered by the kernel.
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.