WebView and JS data transfer for Android development

Source: Internet
Author: User
Tags html form

Inevitably appears in Android development, using a webview to display a H5 page. If you just display the H5 page, this does not require special processing, but in many cases, JS and webview interaction. For example, the data in the HTML form is passed to the activity, the data is verified in the activity, and then uploaded to the server.

So how does JS and WebView interact with each other?

Create a androidhtml project. The main code is as follows:

Mainactivity.java:

    private WebView mWebView;    public static  Final string url_test= "file:///android_asset/index.html";     @SuppressLint (" Javascriptinterface ")      @Override     protected void  OnCreate (bundle savedinstancestate)  {        super.oncreate ( Savedinstancestate);         setcontentview (R.layout.activity_main);         mWebView =  (WebView)  findviewbyid (R.id.webview) ;         websettings settings = mwebview.getsettings ();         settings.setjavascriptenabled (True);         mwebview.loadurl (url_test);         // Addjavascriptinterface There are two parameters in this method, the first parameteris to add an object that encapsulates the native method to invoke in JS, and the second argument is to tell the JS object the name to make it easier to call the native method          Mwebview.addjavascriptinterface (This, "Zzh");//    }    @ The version above javascriptinterface//android 4.2 needs to add this annotation, which means exposing this method to the JS call     public void  callandroidnativemethod (STRING STR) {        LOG.D (" Mainactivity ","---method was executed!!! -"        toast.maketext" (this,  "---" +str, toast.length_ LONG). Show ();     }

Note @javascriptinterface annotations must be added on Android version 4.2. Google's official explanation is that

Caution:if you ' ve set your targetsdkversion to + or higher, you must add the @JavascriptInterface annotation to any meth OD that you want available to your JavaScript (the method must also is public). If you don't provide the annotation, the method is not accessible by your Web page when running on Android 4.2 or higher.

Index.html:

<! doctype html>

The layout in the

Activity_main.xml is:

<?xml version= "1.0"  encoding= "Utf-8"? ><relativelayout    xmlns:android= "Http://schemas.android.com/apk/res/android"     xmlns:tools= "http://schemas.android.com/ Tools "    android:id=" @+id/activity_main "    android:layout_width=" Match_parent "    android:layout_height=" Match_parent "    tools:context = "Com.zzh.androidhtml.MainActivity" >    <Button         android:id= "@+id/button"         android:text= "Java Invoke JS method"         android:layout_width= "Match_parent"          android:layout_height= "Wrap_content"/>    <webview         android:id= "@+id/webview"          android:layout_below= "@+id/button"         android:layout_width= "Match_parent"          android:layout_height= "Match_parent" ></webview></ Relativelayout>

OK, above is JS in how to call the Android native method. Here's how to invoke the JS method in Android native (note that it's inefficient to call the JS method in native to handle business logic in Android, and it's not recommended to handle Android business logic in this way, but also know how to use it).

Private webview mwebview;public static final string url_test= "File:///android_ Asset/index.html "; @SuppressLint (" Javascriptinterface ") @Overrideprotected  void oncreate (bundle  savedinstancestate)  {    super.oncreate (savedinstancestate);     Setcontentview (R.layout.activity_main);    mwebview =  (WebView)   Findviewbyid (R.id.webview);     websettings settings = mwebview.getsettings ( );     settings.setjavascriptenabled (true);     mwebview.loadurl (URL_ TEST);     mwebview.addjavascriptinterface (This, "Zzh");     findviewbyid (R.id.button). Setonclicklistener (New view.onclicklistener ()  {          @Override         public void onclick (View  View) &NBSP;{&NBSP;&NBSP;&NBSP;&NBsp;        mwebview.loadurl ("Javascript:calljavascriptmethod ()");         }    });} The version above the @JavascriptInterface//android 4.2 needs to be added to this annotation, which means exposing this method to the JS call public void  Callandroidnativemethod (STRING&NBSP;STR) {    log.d ("mainactivity", "---method was executed!!!" -");     toast.maketext (this, "---"+str, toast.length_long). Show ();

index.html files are easier

<! doctype html>

The example is simple, the note also writes relatively clearly does not do too much explanation, all by oneself comprehend.

This article is from the "Meu Late injury" blog, please be sure to keep this source http://zzhhz.blog.51cto.com/7107920/1861256

WebView and JS data transfer for Android development

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.