WebView for Android Development

Source: Internet
Author: User

WebView for Android Development
Overview:

A view that displays Web pages. This class is the basis for you to scroll your Web browser or simply display some online content in your Activity. It uses the WebKit rendering engine to display webpages, including forward and backward navigation methods (via history records), amplification and reduction, and text search.

Note: To enable your application to access the Internet and load webpages using WebView, you must add Internet permissions in the Android Manifest file:

 

Class Structure:
java.lang.Object   ? android.view.View     ? android.view.ViewGroup       ? android.widget.AbsoluteLayout         ? android.webkit.WebView
Common Methods:

PublicMethods

WebSettings

GetSettings ()

Obtain the WebSettings object for WebView settings.

Void

SetWebViewClient (WebViewClient client)

Sets the WebViewClient that will receive various notifications and requests.

Void

SetWebChromeClient (WebChromeClient client)

Set chrome processing.

Note:

WebSettings getSettings () gets the WebSettings object for setting WebView.

Common WebSettings methods:

Method

Description

SetAllowFileAccess

Enable or disable WebView to access file data

SetBlockNetworkImage

Whether to display network images

SetBuiltInZoomControls

Set whether scaling is supported

SetCacheMode

Set the buffer Mode

SetDefaultFontSize

Set the default font size

SetDefaultTextEncodingName

Sets the default encoding used during decoding.

SetFixedFontFamily

Set fixed font

SetJavaScriptEnabled

Set whether Javascript is supported

SetLayoutAlgorithm

Set Layout mode

SetLightTouchEnabled

Set the mouse activation Option

SetSupportZoom

Set whether Zoom is supported

Void setWebViewClient (WebViewClient client)

Sets the WebViewClient that will receive various notifications and requests.

Common WebViewClient methods:

Method

Description

DoUpdateVisitedHistory

Update history

OnFormResubmission

The application re-Requests webpage data

OnLoadResource

Load resources provided by the specified address

OnPageFinished

Webpage loaded

OnPageStarted

Webpage loading started

OnReceivedError

Report error information

OnScaleChanged

WebView changed

ShouldOverrideUrlLoading

Control the opening of new connections in the current WebView

Void setWebChromeClient (WebChromeClient client) sets chrome processing.

Common WebChromeClient methods:

Method

Description

OnCloseWindow

Disable WebView

OnCreateWindow

Create WebView

OnJsAlert

Processing the Alert dialog box in Javascript

OnJsConfirm

Process Confirm dialog box in Javascript

OnJsPrompt

Processing the Prompt dialog box in Javascript

OnProgressChanged

Loading progress bar changes

OnReceivedlcon

Webpage icon change

OnReceivedTitle

Webpage Title change

OnRequestFocus WebView

Show focus


Customize WebView, you can add your own behavior:

Create and set the WebChromeClient subclass. This class is called when some user interfaces that may affect the browser occur, such as progress updates and JavaScript alarms are sent here (see debugging tasks. Create and set the WebViewClient subclass. This class is called when Content Rendering is affected, for example, an error or form submission. You can also load the intercepted URL here (through shouldOverrideUrlLoading ()). Modify WebSettings. For example, use setJavaScriptEnabled () to enable JavaScript. Inject Java objects to WebView using addJavascriptInterface (Object, String. This method allows you to inject Java objects into the JavaScript context of a page so that they can access the page through JavaScript.

The following is a more complex example showing error handling, setting, and progress notifications:

 // Let's display the progress in the activity title bar, like the // browser appdoes. getWindow().requestFeature(Window.FEATURE_PROGRESS); webview.getSettings().setJavaScriptEnabled(true); final Activity activity = this; webview.setWebChromeClient(new WebChromeClient() {   public void onProgressChanged(WebView view, int progress) {     //Activities and WebViews measure progress with different scales.     //The progress meter will automatically disappear when we reach 100%     activity.setProgress(progress * 1000);   } }); webview.setWebViewClient(new WebViewClient() {   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();   } }); webview.loadUrl("http://developer.android.com/"); 

Scaling:

You can enable built-in scaling by setting WebSettings. setBuiltInZoomControls (boolean.

Note: Using zooming, if the height or width is not set to WRAP_CONTENT, it may lead to uncertain behavior and should be avoided.

Cookie and window management:

For obvious security reasons, your applications have their own caches, cookie storage, and so on. It does not share the data of browser applications.

By default, HTML requests are ignored to open a new window. This is exactly whether they are opened by JavaScript or by the target link. You can customize your WebChromeClient to provide your own behavior to open multiple windows and render them in any way you want.

Construct a Web application in WebView:

If you want to provide a Web application (or just a Web page) as part of the client application, you can use WebView to do this. The WebView class is an extension of the Android View class. It allows you to display webpages as part of your activity layout. It does not include any function of a fully developed Web browser, such as a navigation control or an address bar. By default, all webviews display a Web page.

A common scenario for using WebView: When you want to provide information that may need to be updated in your application, such as an end user protocol or user guide, therefore, using WebView is very helpful. In your Android Application, you can create an Activity that contains WebView and use it to display online hosted documents.

Another common scenario for WebView is that if the data provided by your application always needs to be obtained from the Internet, such as email. In this case, you may find that it is easier for your Android app to display all the user data on the webpage, instead of executing a network request and then parsing ?? Data, and render it in the Android layout to create a WebView. Instead, you can design a webpage specifically designed for Android devices, and then implement the WebView to load the webpage in your Android app.

The following will show you how to start using WebView and how to do some additional things, such as processing page navigation in your Android Application and binding JavaScript to the client code from the webpage.

Basic usage:

By default, WebView does not provide browser-like widgets, and JavaScript and web page errors are ignored. If your purpose is to display some HTML as part of the user interface, this may be good; users no longer need to interact and read with the web page, and the web page does not need to interact with the user. If you need a comprehensive Web browser, you may need to call the browser application to load the URL, instead of displaying it in WebView. For example:

1) Add a WebView in your APP:

 
 
2) load a web page using the loadUrl () method:

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.loadUrl("http://www.example.com");

3) add network access permissions to applications:

     
   
 
The preceding steps show all the basic web pages.

Use JavaScript in WebView:

If you plan to use JavaScript when loading Web pages in your WebView, you must enable JavaScript for your WebView. Once JavaScript is enabled, you can also create interfaces between your application code and JavaScript code.

JavaScript is disabled by default in WebView. You can enable WebSettings attached to WebView. That is, use getSettings () to get WebSettings, and then use setJavaScriptEnabled () to enable JavaScript.

WebView myWebView = (WebView) findViewById(R.id.webview);WebSettings webSettings = myWebView.getSettings();webSettings.setJavaScriptEnabled(true); 

The JavaScript code is bound to the Android code:

When developing a web application and specially designed WebView in your Android Application, you can create interfaces between your JavaScript code and the Android code on the client. For example, your JavaScript code can call a method in your Android code to display the Dialog, instead of using the JavaScriptalert () method.

Call addJavascriptInterface () to bind a new interface between JavaScript and Android code. By binding a class instance to your JavaScrip, JavaScript can call an interface name called the callback class.

public class WebAppInterface {    Context mContext;    /** Instantiatethe interface and set the context */    WebAppInterface(Context c) {        mContext = c;    }    /** Show a toastfrom the web page */    @JavascriptInterface    public void showToast(String toast) {        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();    }}

Note: If the targetSdkVersion you set is 17 or higher, you must add @ JavascriptInterface to add annotation for any JavaScript (this method must be public) method you want to provide to you. If you do not provide annotations, this method cannot be accessed by web pages when running on Android4.2 or later.

In the preceding example, the WebAppInterface class allows a webpage to call the showToast () method to create a Toast message.

You can use the addJavascriptInterface () method and Android interface name to bind this class to JavaScript running in your WebView.

WebView webView = (WebView) findViewById(R.id.webview);webView.addJavascriptInterface(new WebAppInterface(this), "Android");

This creates an interface named Android for JavaScript running in WebView. At this point, Web applications can access the WebAppInterface class. For example, some HTML and JavaScript will create a Toast message when you click the button.

<script type="text/javascript">    function showAndroidToast(toast) {        Android.showToast(toast);    }</script>

You do not need to initialize Android from the JavaScript interface. WebView automatically applies it to your web page. Therefore, use the Android interface to call the WebAppInterface. showToast () method by pressing the showAndroidToast () method.

Note: bind your JavaScript Object to run in another thread, instead of the thread built in it.

Warning using addJavascriptInterface () will allow JavaScript to control your Android application. This is a very useful feature or a dangerous security issue. When the HTML of WebView is untrusted (for example, some or all of the HTML is provided by an unknown person or process ), the attacker executes any client code included in HTML and selected. Therefore, addJavascriptInterface () should not be used unless all HTML and JavaScript you write appear in your WebView. You should also not allow users to navigate to other webpages that are not their own, within your WebView (Instead, allow users to open external links through the default browser application. The web browser of the application opens all URL links, so be careful that you only need to describe the following parts in the processing page navigation ).

Processing page navigation:

When you click a link on WebView, the default action is to start an Android app that processes URLs. Generally, Web browsers are opened and installed in the destination URL by default. However, you can overwrite this behavior for WebView to open the link on your WebView. Then, you can allow users to view the web page history record retained by your WebView.

To open the user click link, you only need to provide a WebViewClient for your WebView and use setWebViewClient ().

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new WebViewClient());

In this way. All the links clicked by the user are loaded on your WebView.

If you want to control the loading of click links, create your own WebViewClient override shouldOverrideUrlLoading () method.

private class MyWebViewClient extends WebViewClient {    @Override    public boolean shouldOverrideUrlLoading(WebView view, String url) {        if (Uri.parse(url).getHost().equals("www.example.com")) {            // This is my web site, so do not override;let my WebView load the page            return false;        }        // Otherwise, the link is not for a page on my site, so launch anotherActivity that handles URLs        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));        startActivity(intent);        return true;    }}

Create a new WebViewClient instance for WebView:

WebView myWebView = (WebView) findViewById(R.id.webview);myWebView.setWebViewClient(new MyWebViewClient());

Now, when a user clicks a link, the system calls shouldOverrideUrlLoading () to check whether a specific domain of the URL host matches (defined as above ). If this parameter does not match, false is returned in order to load the URL that is not overwritten (it allows the URL to be loaded by WebView as usual. If the host in the URL does not match, an Intent will be created to start the default Activity processing URL (which can solve the user's default Web browser ).

History of Web browsing:

When your WebView loads a URL with a heavy load, the WebView automatically accumulates the history of the accessed webpage. You can use the goBack () and goForward () Methods to browse backward and forward.

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {    // Check if thekey event was the Back button and if there's history    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {        myWebView.goBack();        return true;    }    // If it wasn'tthe Back key or there's no web page history, bubble up to the default    // systembehavior (probably exit the activity)    return super.onKeyDown(keyCode, event);}

Returns true if there is a canGoBack () method accessed by the user with an actual web page history. Similarly, you can use canGoForward () to check for historical advances. If this check is not performed, GoBack () or goForward () will not do anything once the user reaches the end of history.

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.