Android Web App official documentation translation Chapter 3: WebView building applications

Source: Internet
Author: User

Document Content
Add WebView to your application
Using JavaScript in Webview
○ Enable JavaScript
○ Bind JavaScript code to Android code
Process page navigation
○ History navigation
Key classes
WebView
WebSettings
WebViewClient
Related Manual
Web View
If you want to publish a web app (or just a web page) as part of the client, you can use WebView. WebView is an extension of View in Android, allowing you to use web pages as your activity layout ). It does not contain the complete functions of a browser, such as navigation control or address bar. By default, WebView only displays a Web page.
A common scenario of using WebView is when you want to provide some information that you may need to update in the application, such as the end user protocol or user guide. In your Android app, you need to create an Activity that contains WebView, and then use it to show your documents on the Internet.
Another scenario of using WebView is that you need to connect to the network to obtain data, such as email, when providing data for users. In this case, you may find it easier to build a WebView in an Android app to display the web pages that provide relevant data, rather than trying to connect to the network to obtain data, parse the data and place it in the Android layout. You can design a web page for Android devices and implement a WebView in Android to load the page.
This document shows how you can start using WebView and do some additional things, such as page navigation, binding Javascript code in web pages to the Code in your Android app.
Add WebView to your application
To add a WebView to your application, you only need to add elements to your activity layout. For example, the following is a layout file in which the WebView is full of the screen.
<? Xml version = "1.0" encoding = "UTF-8"?>
<WebView xmlns: android = "http://schemas.android.com/apk/res/android"
Android: id = "@ + id/webview"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
/>
To load the page in WebView, use loadUrl (). For example:
WebView myWebView = (WebView) findViewById (R. id. webview );
MyWebView. loadUrl ("http://www.example.com ");
Before it works effectively, you must ensure that your application can access the network. To access the network, you must obtain INTERNET permission in your configuration file. For example:
<Manifest...>
<Uses-permission android: name = "android. permission. INTERNET"/>
...
</Manifest>
This is all you need to do to apply a WebView to display basic web pages.
Use JavaScript in WebView
If you want to use Javascript to load web pages in WebView, You need to enable Javascript in WebView. Once Javascript is enabled, you can create interfaces between your application code and your Javascript code.
Enable JavaScript
You can enable WebSettings in WebView. You can use getSettings () to obtain the WebSettings value, and then use setJavaScriptEnabled () to enable JavaScript.
For example:
WebView myWebView = (WebView) findViewById (R. id. webview );
WebSettings webSettings = myWebView. getSettings ();
WebSettings. setJavaScriptEnabled (true );
WebSettings also provides many other useful settings. For example, if you are developing a web app dedicated to WebView in Android applications, you can use setUserAgentString () to define a custom user proxy string (custom user agent string ), then, query the Custom User Agent on the web page to confirm that the client requesting your web page is indeed an Android Application.
Bind JavaScript code to Android code
When developing a WebView web app for Android applications, you can create an interface between your Javascript code and the Android code on the client. For example, your Javascript code can call the method in Android code to display a Dialog, instead of using the alert () function in Javascript.
To bind a new interface between your Javascript and Android code, you need to call addJavascriptInterface () and pass it to a class instance to bind it to Javascript, and an interface name that allows Javascript to call for the callback class.
For example, you can include the following classes in your Android app:
Public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface (Context c ){
MContext = c; www.2cto.com
}
/** Show a toast from the web page */
Public void showToast (String toast ){
Toast. makeText (mContext, toast, Toast. LENGTH_SHORT). show ();
}
}
In this example, JavaScriptInterface allows the web page to use the showToast () method to create a Toast message.
You can bind this class to the Javascript running in WebView through addJavascriptInterface () and name the interface Android. For example:
WebView webView = (WebView) findViewById (R. id. webview); webView. addJavascriptInterface (new JavaScriptInterface (this), "Android ");
This Code creates an Android interface for Javascript running in WebView. At this time, your web app will be able to access the JavaScriptInterface class. For example, the following are some HTML and Javascript. When a user clicks a button, they use this new interface to create a toast message:
<Input type = "button" value = "Say hello" onClick = "showAndroidToast ('Hello Android! ') "/>
 
<Script type = "text/javascript">
Function showAndroidToast (toast ){
Android. showToast (toast );
}
</Script>
There is no need to initialize the Android interface from Javascript. WebView will automatically make it available for your web page. Therefore, when you press the button, the showAndroidToast () function uses this Android interface to call the JavaScriptInterface. showToast () method.
Note: The object bound to your Javascript runs in another thread, rather than in the thread that created it.
Be careful: Using addJavascriptInterface () allows Javascript to control your Android applications. This is a double-edged sword. It is useful and may also pose security threats. When HTML in WebView is untrusted (for example, some or all of HTML is provided by an unknown person or process ), then an attacker may use HTML to execute any code he wants on the client. Therefore, addJavascriptInterface () should not be used unless all HTML and Javascript in WebView are written by yourself. Similarly, you should not allow users to direct their webviews to another web page that is not yours (on the contrary, enable the user's default browser application to open external links-All URL links are opened by the user's browser by default, so be sure to handle the page navigation carefully, as described in the following section .)
Process page navigation
When a user clicks a page link in a WebView, Android starts an application that can process the URL by default. Generally, the target URL is opened and loaded by the default browser. However, you can overwrite this line in WebView, And the link will be opened in WebView. In this way, you can let the user forward or backward by saving the browsing record in the WebView.
To enable users to click the open link, you only need to use setWebViewClient () to provide a WebViewClient for WebView. For example:
WebView myWebView = (WebView) findViewById (R. id. webview );
MyWebView. setWebViewClient (new WebViewClient ());
In this way, you can. Now all links clicked by users are directly loaded in WebView.
If you want to have more control over the location of the loaded link, you can create your own WebViewClient to overwrite the shouldOverrideUrlLoading () method. For example:
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 another Activity 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 you click a link, the system will call shouldOverrideUrlLoading () to check whether the URL host matches a specific domain (as defined above ). If it matches, the method returns false instead of overwriting URL loading (it still makes WebView load the URL as usual ). If they do not match, an Intent will be created to load the default Activity to process the URLs (parsed by the user's default web browser ).
History navigation
When your WebView overwrites URL loading, it will automatically generate historical access records. You can use goBack () or goForward () to access the visited site either forward or backward.
For example, the following code uses Activity to use the device's back button to navigate backward:
@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
// Check if the key event was the BACK key and if there's history
If (keyCode = KeyEvent. KEYCODE_BACK) & myWebView. canGoBack (){
MyWebView. goBack ();
Return true;
}
// If it wasn' t the BACK key or there's no web page history, bubble up to the default
// System behavior (probably exit the activity)
Return super. onKeyDown (keyCode, event );
}
If a historical access record is available for access, the canGoBack () method returns true. Similarly, you can use canGoForward () to check whether forward access history exists. If you do not perform this check, goBack () or goForward () will not do anything once the user accesses the last record.

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.