Android API Guides web App--------------Building Web Apps in WebView (WebView binding to pages)

Source: Internet
Author: User

If you want to implement a web app on your phone or download a Web page in your app, you'll need to use the WebView control. This WebView class is an extension subclass of the view class that allows Web pages to be displayed as part of the application layout. It is those features that do not have a complete browser, such as WebView no navigation bar, address bar, etc. WebView's default function is to look for WebView.

When you add something to your app that might later be new (such as a user agreement or user Guide), you are using webview that is very helpful. In your app, you can create an activity with WebView and then show your online document information.

Another case where using WebView is that when you provide data to the user, you always need to connect to the server to retrieve data, such as mail. You will find it easier to use WebView to display user data in the app than to request the network each time and then parse the data and show it in layout. You can design Web pages for Android devices and then use WebView to load them in your Android app.

This article shows how to get started with WebView and use it to do some extra things. For example, in your Android app to handle page navigation and to bind the JS in your page to the client code.

Adding a WebView to Your application

Add <WebView> in your layout to add WebView to your app. For example, here is a webview that fills the entire 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 "/>

Load page UseloadUrl()方法,例如

WebView Mywebview = (WebView) Findviewbyid (R.id.webview);
Mywebview.loadurl ("http://www.example.com");

Note that you must set Internet permissions in the manifest file before it can be used.

<manifest >     <uses-permission android:name= "Android.permission.INTERNET"/>     ... </ Manifest>


This is the most basic aspect that WebView needs to show the page.

Using JavaScript in WebView (use JS in WebView)

If you webview inside the page to use JS, then you need to enable JS in your webview. Once you have JS enabled, you can also wear an interface between your app code and the JS code.

Enabling JavaScript

In WebView JS default is not available, you should be WebSettings able to set up your webview, so that it can use JS. You can do this by using the WebViewgetSettings()方法得到WebSettings的返回值,然后调用WebSettings的setJavaScriptEnabled()方法来设置使用js。

例如

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); WebSettings websettings = Mywebview.getsettings (); Websettings.setjavascriptenabled (TRUE);

WebSettings offers a variety of settings that you think are useful. If you use WebView in your app to develop a web app, you can set up a user agent string by using setuseragentstring (). Then query this user agent header on your Web page to verify that this page request is really your app.

From the Android SDK tool/Catalog

Binding JavaScript code to Android code

当你在你的app应用里使用WebView开发web应用,你能够在js代码和客户端代码之间去创建接口。例如,js代码去调用你的Android里面的一个方法,去弹出弹框来去替代使用js的alter。

通过调用addJavascriptInterface()方法,可以在js代码和Android代码之间绑定一个接口,它可以把一个实例绑定到js,js可以通过这个接口的名字去调用这可实例。

例如下面:

public class Webappinterface {    Context mcontext;      /** instantiate the interface and set the context *     /webappinterface (context c) {         mcontext = c;     }      /** Show A toast from the Web page *    /@JavascriptInterface public     void Showtoast (String toast) {         Toast.maketex T (Mcontext, Toast, Toast.length_short). Show ();     }

Warning: If your SDK version is 17 or higher, you must add a @JavascriptInterface comment before any methods you want to invoke in JS (this method must be public). If you do not provide this annotation, then this method will not work on 4.2 or later versions.

This example is the Webappinterface class allows webview pages to wear a toast message using the Showtoast method. , you can use the WebView add JavascriptInterface() to bind this class to your JS, and the name of this interface is "Android". For example:

WebView WebView = (WebView) Findviewbyid (R.id.webview); Webview.addjavascriptinterface (New Webappinterface (This), "Android");


JS running in WebView through "Android" to call this created interface, then your web app can access the Webappinterface class. For example, here are some HTML code that, when clicked by a button, JS calls this new interface interface to create a toast.

  <input type= "button" value= "Say Hello" onclick= "showandroidtoast (' Hello android! ')"/>   <script type= " Text/javascript ">      unction showandroidtoast (toast) {         android.showtoast (toast);      }  </script>

You do not need to initialize this "Android" interface in JS. WebView will automatically enable it to be used in Web pages. So, by clicking on this button, the Showandroidtoast () will use the Android interface to call the Webappinterface.showtoast () method.

Note: This object is bound on JS to run in another thread, not in the thread he was created in.

Warning:

After using this addjavascriptinterface () method, JS is allowed to control your Android app. This can be a very dangerous feature, even if it is a very useful feature. In WebView, HTML is unreliable (for example, some or all of the HTML may be provided through a person or program that you don't know). Attack this can execute your client's code and select any code in your HTML. If so, you can not use addJavascriptInterface() , unless you webview HTML and JS are all written by yourself. You should prohibit users from WebView to jump to other third-party pages that are not on their own page. (To replace these, the default user's browser can open all the URL links, so if you handle the page jump, if you have the situation described below, you should be extra careful attention).

Handling page Navigation (handling pages jump)

When a user clicks a link from your WebView, the default is to load an app to process the URL, usually the default browser to open and load the URL. However, you can overwrite this with the default behavior in the WebView, and let the URL open in your own webview. You can then jump backwards or forwards through webview to maintain access records for Web pages.

Use the Setwebviewclient (). method to provide a webviewclient that allows the user to open the link in their own webview.

Example:

WebView Mywebview = (WebView) Findviewbyid (R.id.webview); Mywebview.setwebviewclient (New Webviewclient ());


After doing this, all URLs will be opened in your webview.

If you click on the link and you want to do more color things, you will need to rewrite WebViewClient the shouldoverrideurlloading ();

Instance:

Private class Mywebviewclient extends Webviewclient {     @Override public      boolean shouldoverrideurlloading ( WebView view, String URL) {         if (uri.parse (URL). GetHost (). Equals ("www.example.com")) {             //This was my web site, so D o not override; Let my WebView load the page             return false;         }         Otherwise, the link isn't for a page in my site, so launch another Activity that handles URLs          Intent Intent = new Intent (Intent.action_view, Uri.parse (URL));         StartActivity (intent);          return true;     } }


Then create a webview for the WebViewClient 的一个实例

WebView Mywebview = (WebView) Findviewbyid (R.id.webview);  Mywebview.setwebviewclient (New Mywebviewclient ());


Now, when you click on the link, the system will call Shouldoverrideurlloading () and check if the host of the URL matches a specific domain name (as above). If it does not match this method will return false, in order not to overwrite the URL load, if the URL does not match, it will be able to load the URL by default activity.

Navigating Web page history (Browse historical page)

When your webview makes a copy of the URL load, he will record the Access history page himself. You can use the GoBack () and G oForward() . method to jump forward or backward through this historical record.

For example, here is an action that clicks the back button to roll back the page.

@Override Public  boolean onKeyDown (int keycode, keyevent event) {      //Check If the key event is the back button an D 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 Exi t the activity)      return Super.onkeydown (KeyCode, event);  }

If the user goes to visit the history page CanGoBack () will return true, the same you can also use canGoForward() to access the history of the forward. If you do not perform this search, GoBack () and G oForward() will not do anything once the user reaches the end of the history record.


Android API Guides web App--------------Building Web Apps in WebView (WebView binding to pages)

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.