Talking about the interactive _android of the Android program and JavaScript script

Source: Internet
Author: User

As we all know, what is the main sign of the advent of the mobile phone age? Easy access to the internet! The way the internet shows us is typically web pages, and it's essential to have JavaScript in the Web, so it's urgent that Android provides support for JavaScript, and thankfully, Android has already provided us with seamless connectivity. Allows us to interact with JavaScript through Android.

Our application is very simple, as shown in the figure:

We have an input box with a button next to it, and the click button prompts us to enter the content. Of course this is just the simplest program in HTML, but you'll try it on the Android phone and it won't be prompted. In order for it to prompt the user in Android, we need to use the interaction of Android and JavaScript. Yes, here's a Web page, the code is as follows:

Js.html

 
 

Take a look at our activity code again:

Package cn.com.chenzheng_java.js; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.util.Log; 
Import Android.webkit.JsResult; 
Import android.webkit.WebChromeClient; 
Import android.webkit.WebSettings; 
Import Android.webkit.WebView; 
 
Import Android.widget.Toast; 
 public class Javascriptactivity extends activity {WebView WebView; 
 
 Handler Handler = new Handler (); 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 
  Setcontentview (R.layout.main); 
  WebView = (webview) Findviewbyid (R.ID.WEBVIEW1); /** * WebSettings holds the state information in the WebView. When WebView is created for the first time, the Websetting store is the default value. Websetting and WebView are one by one bound. 
   If the WebView is destroyed, then * we will throw an exception when we call the method in Websetting again. 
  * * WebSettings websettings = webview.getsettings (); 
  Websettings.setjavascriptenabled (TRUE); 
 
  Webview.loadurl ("file:///data/js.html"); /*** *webchromeclient is a more magical thing, which provides a series of methods, which are used in our JavaThe script code executes when it calls a particular method, and we typically switch the JavaScript form display to Android in its internal *. 
   * For example: We rewrite the Onjsalert method, then when the page needs to pop up the alert window, it executes our code and prompts the user in the form of our toast. */class Mywebchromeclient extends Webchromeclient {@Override public boolean onjsalert (WebView view, String URL, String message, jsresult result) {Toast.maketext (Getapplicationcontext (), message, Toast.length_lo 
    NG). Show (); 
   return true; 
  } webview.setwebchromeclient (New Mywebchromeclient ()); 
   * * To provide JavaScript with a callback interface, note here, must be implemented in a separate thread, do not block the thread's * addjavascriptinterface (Object obj, String InterfaceName) * obj Represents a Java object, where we typically implement a class of our own that provides the method we want to provide to JavaScript access * InterfaceName is the JS object used to access the method we declared in obj. Call mode is Window.interfacename. Method name ()/Webview.addjavascriptinterface (new Object () {public void Show () {ha 
      Ndler.post (New Runnable () {@Override public void run () {LOG.I ("notification", "called The Method Oh"); * * through Webview.loadurl ("javascript:xXX ") method can call the current Web page in the name * for XXX JavaScript methods/Webview.loadurl (" Javascript:show () "); 
 
   } 
    }); 
 
 }, "Chenzheng_java"); 

 } 
}


Attention:

1 to allow WebView to load the Assets,android SDK from the APK file provides a schema, prefixed with "file:///android_asset/". WebView encounters such a schema, it goes to the assets directory in the current package to find content. As the "file:///android_asset/demo.html" above

2 Java objects and methods to be bound in the Addjavascriptinterface method to run another thread, it cannot be run in the thread that constructs him, which is also the purpose of using handler.

3 If you want to access the network, please add permissions in the Androidmanifest.xml <uses-permission android:name= "Android.permission.INTERNET" ></ Uses-permission>

Api
as we can see in the program, Android's access to Web pages and the interaction with JavaScript are mainly used in a few categories:

WebView: We can think of it as a browser, the user visited the URL to parse, download, render ..., and then return to the User a Web page. It uses the WebKit rendering engine internally, and it includes features that we often use, such as zooming in and out of the page (you need to set the Websettings.setbuiltinzoomcontrols (Boolean) in websetting); Back off.......

By default, WebView is ignored for both JavaScript and page errors. Most of the time, if we want to load a URI, maybe we'll use this form more:

Uri uri = uri.parse ("http://www.example.com"); Intent Intent = new Intent (Intent.action_view, URI); StartActivity (Intent);

The API provides us with an example of loading a page via WebView,

We can see that there are mainly Loadurl () and LoadData () methods. Here, please note the meaning of each parameter Oh,

Expand

In addition, Android provides us with a number of classes to assist in the use of our webview.

Webviewclient:

。 Webviewclient is to help WebView handle various notices and request events, specifically including:

    • Onloadresource: Notifies WebView to load the resource specified by the URL
    • Onpagestart: Trigger when page starts loading
    • Onpagefinish: Triggered when the page finishes loading
    • Onreceiveerror: Triggered when an error occurs
    • Webchromeclient:

Webchromeclient is the Auxiliary webview Processing JavaScript dialog box, website icon, website title, loading progress, etc.

    • Onclosewindow (Close WebView)
    • Oncreatewindow ()
    • Onjsalert (WebView on alert is not going to come out, need to customize your webchromeclient processing pop-up)
    • Onjsprompt
    • Onjsconfirm
    • Onprogresschanged
    • Onreceivedicon
    • Onreceivedtitle

The API provides us with an example:

Websetting: And WebView are one by one bound to control some of the underlying settings of WebView information, such as whether to identify JavaScript, whether the Web page can be zoomed in and out.

If we want to view history pages through WebView, it is important to note that the following methods are used to determine whether the operation can be done:

And then you can go through

    • void GoBack ()
    • void Gobackorforward (int steps)
    • void GoForward ()

Three methods to operate, the literal meaning is easy to understand, where Gobackorforward passed into the negative when the back operation, positive numbers for the forward operation.

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.