Android builds Web application on WebView

Source: Internet
Author: User

Original link: http://developer.android.com/guide/webapps/webview.html

Reference:http://developer.android.com/reference/android/webkit/webview.html

If you want to implement a web app (or just a Web page) as part of your app, you can use WebView to implement it. WebView is an extension of the Android view class that allows you to display a Web page as part of the activity layout. It does not contain some features of a mature browser, such as navigation controls or input fields. By default, WebView displays a Web page.
A common occasion for using WebView is when you want to provide information that needs to be updated frequently in your app, such as user agreements or user manuals. In Android apps, you can create an activity that contains a webview, and then use it to display documents that are available online.
Another occasion to use WebView is if your app always needs a web link to get the data and provide it to the user, such as e-mail. At this point, you can find that creating a WebView in your app and using a Web page to display user data is more convenient than performing a network request, parsing the data, and then rendering it to the Android layout. You just need to design the page based on your Android device, then implement a webview in your app and load the Web page you just designed.
This document will teach you how to start learning WebView and implement some other features, such as page navigation and binding JavaScript to Web pages.


Add a webview to your app to add a webview to your app, you just need to include webview tags in your activity layout file. For example, here is a webview filled screen layout

<?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 a Web page in WebView, you can use the Loadurl () method, for example

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.loadurl ("http://www.baidu.com");
Before this code runs, you need to be plugged into the Internet. You only need to add Internet access to your manifest file.

<uses-permission android:name= "Android.permission.INTERNET"/>
These are the basics of displaying a Web page.


Using JavaScript in WebView if you want to load a webpage that implements JavaScript, you must turn on JavaScript in WebView. When JavaScript is useful, you can also create interfaces between your app code and JavaScript code.
JavaScript on WebView is not turned on by default in JavaScript. You can open it by adding websettings to WebView. You can use the GetSettings () method to get the websettings, and then use setjavascriptenabled () to turn it on. For example:
WebView Mywebview = (WebView) Findviewbyid (R.id.webview); WebSettings websettings = Mywebview.getsettings (); websettings.setjavascriptenabled (true);

You can find a lot of useful features in websettings. For example, if you use WebView to develop a Web application, you can use the Setuseragentstring () method to define a custom user-agent string, which can then be queried by a custom user agent in the Web page to identify whether the current request page is your Android app.


Binding JavaScript code to Android source you can create an interface between JavaScript and Android source when you create a Web application using WebView in your app, for example, Your JavaScript code can call the method defined in Android to display a dialog box, not the alert () method for JavaScript.
For example, you can add the following classes to your app:

public class Javascriptinterface {context mcontext;/** instantiate the interface and set the context */javascriptinterface (Context c) {mcontext = c;} /** Show A toast from the Web page */public void Showtoast (String toast) {Toast.maketext (Mcontext, Toast, toast.length_s Hort). Show (); }}
In this example, the Javascriptinterface class uses the Showtoast () method to create a toast message.
You can bind this class into JavaScript and use the Addjavascriptinterface () method in WebView to run and create an interface with the name Android.

WebView WebView = (WebView) Findviewbyid (R.id.webview); Webview.addjavascriptinterface (new Javascriptinterface (this) , "Android");
This code creates a JavaScript interface called "Android" and runs in WebView. Here, your web app will be plugged into the Javascriptinterface class. For example, here is the HTML JavaScript code that creates a toast message using the new interface when the user taps the button.

<input type= "button" value= "Say Hello" onclick= "showandroidtoast (' Hello android! ')"/><script type= "text/ JavaScript > function Showandroidtoast (toast) {android.showtoast (toast);} </script>
You don't need to initialize the Android interface from JavaScript. WebView will automatically allow him to use it on the web. Therefore, the Showandroidtoast () method calls the Javascriptinterface.showtoast () method using the Android interface when the button is clicked.
Notes: An object that is bound in JavaScript runs on another thread, and it is a different thread than the thread that created it.
watch out.: Using java.lang.String) Addjavascriptinterface () allows JavaScript to control Android apps. This is a very useful and dangerous. When HTML in the WebView is not trusted (for example, some content in HTML is provided by a person or thread that is not known), an attacker can arbitrarily control the HTML code that executes on the client. Similarly, you should not use the java.lang.String) Addjavascriptinterface () method except that you need to write HTML or JavaScript in WebView. You also can't allow users to manipulate pages in WebView other than themselves (instead, you should let the user invoke the default browser to open the external connection--in general, the user's Web browser will open all the URL links, so only if the manipulated Web page is described in the following section).


Handling page navigation When a user clicks a link in your WebView, the default action for Android is to start an app to capture it. Typically, the default Web browser opens and loads the destination URL. However, you can rewrite the action in WebView and open the link in your webview. You can also let users handle the fallback and forward functions of their history.
Open the link that the user clicked, only provide webviewclient in WebView, use the Setwebviewclient () method. For example:

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.setwebviewclient (new Webviewclient ());
Complete, now all the links that the user taps are opened in WebView. If you want to do more when you click on the link and load the page, create your own webviewclient and rewrite the java.lang.String) shouldoverrideurlloading () method. For example:
Private class Mywebviewclient extends Webviewclient {@Override public boolean shouldoverrideurlloading (WebView view, STR ing URL) {if (Uri.parse (URL). GetHost (). Equals ("www.example.com")) {//This is my page, so do not rewrite, let my webview load it return false;}// If it is not my Web page, start another activity to process the urlintent intent = new Intent (Intent.action_view, Uri.parse (URL)); StartActivity (Intent); return true; }}
Then create an instance of Webviewclient for WebView.
WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.setwebviewclient (new Mywebviewclient ());
Now when the user clicks on a link, the system calls Java.lang.String) Shouldoverrideurlloading (), which will tell if the URL host is going to match the specified domain name (as we enumerated above). If it does not match, the method returns False, and a intent creates and starts the default activity to process the URL (which generally resolves to the user's default browser).


Manipulating page history when your webview rewrites the URL, it automatically accumulates the page history you've visited. You can use the GoBack () method and the GoForward () method to manipulate the fallback and forward functions. For example, the following is activity using the return button action "fallback" function.

@Overridepublic boolean onKeyDown (int keycode, keyevent event) {//Check if the key event is the back button and if there ' s historyif ((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 A ctivity) return Super.onkeydown (KeyCode, event);}
If there is a page history then the CanGoBack () method returns True, and similarly, you can use CanGoForward () to check if there is a "forward" history. If you do not perform this check, GoBack () and GoForward () do nothing when the user reaches the end of history.

Android builds Web application on WebView

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.