Android API Guides web app ------------ Building Web Apps in WebView (WebView and page binding)

Source: Internet
Author: User

Android API Guides web app ------------ Building Web Apps in WebView (WebView and page binding)

If you want to implement a web app on your mobile phone or load a web page in the app, you need to use the WebView control. This WebView class is an extension subclass of the View class. It allows web pages to be displayed as part of the application layout. It does not have the features of a complete browser, such as WebView without navigation bar or address bar. The default function of WebView is to find WebView.

When you add new information (such as user protocols or user guides) to your app, It is very helpful to use WebView. In your application, you can create an activity with WebView and display your online document information.

WebView is a suitable scenario where you always need to connect to the server to retrieve data, such as emails, when providing data to users. You will find it easier to use webView to display user data on the web page in the application than to request the network each time and then parse the data and display it in layout. You can design web pages for Android devices and load them using WebView in your Android applications.

This article shows how to start using WebView and use it to do some additional things. For example, you can process page navigation in your Android app and bind js in your page to the client code.

 

Adding a WebView to Your Application

Add You can add the WebView to your application. For example, the following is a WebView filled with the entire screen.

 
  
 

Load page usageLoadUrl () method, such

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

Note that you must set INTERNET permission in manifest file before using it.

      
  
        ... 
  
 


This is the most basic aspect for WebView to display pages.

Using JavaScript in WebView (Using js in WebView)

If you want to use js to load pages in your WebView, You need to enable js in your WebView. Once you enable js, you can wear an interface between your application code and js Code.

Enabling JavaScript

In WebView, js cannot be used by default. You can useWebSettingsSet your WebView so that it can use js. You can use WebView'sGet the getSettings () methodWebSettingsAnd then callWebSettingsSetJavaScriptEnabled () method to set the js.

For example

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

WebSettings provides various permissions that you think are useful. If you use WebView in your application to develop and design a Web app, you can use setUserAgentString () to set a user proxy string, then query the user proxy header on your web page to verify that the page request is indeed your app.

From the Android SDK tool/directory

Binding JavaScript code to Android code

When you use WebView to develop web applications in your app, you can create interfaces between js Code and client code. For example, js Code calls a method in your Android system and pops up a dialog box to replace the js alter.

By calling the addJavascriptInterface () method, you can bind an interface between js Code and Android code. It can bind an instance to js, js can call this instance through the interface name.

For example:

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.makeText(mContext, toast, Toast.LENGTH_SHORT).show();     } }

Warning If your sdk version is 17 or higher, you must add@ JavascriptInterfaceNote (this method must be public ). If you do not provide this annotation, this method will not run on version 4.2 or later.

This instance is a WebAppInterface class that allows the WebView page to wear a Toast information using the showToast method ., You can use add of WebViewJavascriptInterface()Bind this class to your js, and the interface name is "Android". For example:

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


The js running in WebView calls the created interface through "Android". In this case, your web app can access the WebAppInterface class. For example, here is some html code. When you click the button, js calls this new interface to create Toast.

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

You do not need to initialize this "Android" interface in js. WebView automatically enables it to be used on web pages. Therefore, click this button. This showAndroidToast () will use the Android interface to call the WebAppInterface. showToast () method.

Note: This object is bound to js and runs in another thread, not in the thread he created.

 

Warning:

With this addJavascriptInterface () method, js is allowed to control your Android application. This may be a very dangerous feature even if it is very useful. In webview, html is unreliable (for example, some or all of html may be provided by an unknown person or program ). Attackers can execute your client code in your html and select any code. In this case, you cannot useaddJavascriptInterface()Unless your WebView html and js are all written by yourself. You should prohibit users from redirecting to other third-party pages that are not their own pages in WebView. (To replace these, the default user's browser can open all url links. Therefore, if you are dealing with page jumps, if there is a situation described below, you should be especially careful ).

Handling Page Navigation)

 

When a user clicks a link from your webview, an app to process a url is loaded by default. This url is usually opened and loaded by the default browser. However, you can overwrite the default behavior in the webview so that the url can be opened in your own webview. Then, you can jump back or forward to access the Web page maintained by webview.

Use setWebViewClient (). To provide a WebViewClient, which allows you to open a link in your own webView.

Example:

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

 

After this is done, all URLs will be opened in your WebView.

If you click the link and want to perform other multi-color tasks, you need to rewrite them.WebViewClientShouldOverrideUrlLoading ();

Instance:

 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 WebView WebViewClient An instance

 

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


Now, when you click the link, the system will call shouldOverrideUrlLoading () to check whether the host of this url matches a specific domain name (such as the above ). If this method does not match, false is returned. In order not to overwrite the url load, if the url does not match, the system will jump to the activity that can load this URL by default.

 

Navigating web page history)

 

 

When your WebView rewrites url loading, it records the accessed history page by itself. You can use goBack () and goForward(). Method, jump forward or backward through this history.

For example, here is an operation to roll back the web page by clicking the back button.

@Override  public boolean onKeyDown(int keyCode, KeyEvent event) {      // Check if the key event was the Back button 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 you access the history page canGoBack (), true is returned. You can also usecanGoForward()Forward access history. If you do not perform this search, once the user reaches the end of the historyoForward()No operation is performed.

 

 

 

 

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.