WebView between JS and Android native functions

Source: Internet
Author: User

Introduced

With the popularity of HTML5, HTML is not necessarily more expressive than the original application, and has a strong extension of compatibility, so more and more applications are using HTML and Android native hybrid development model implementation.

Since the implementation of hybrid development, JS and Android native functions of the mutual invocation is necessary. A demo is written here, which allows you to display the images in the HTML by clicking on them locally.

Principle

1, Android Call JS is very simple, direct webview.loadurl ("Javascript:js Method Name ()");

2, JS call Android method, need to use Webview.addjavascriptinterface (Object obj, String InterfaceName) This method tells WebView I want to add a JS interface call local function.

3, the demo uses the Universalimageloader and the Photoview implementation picture loading and browsing

See http://www.cnblogs.com/leestar54/p/4220068.html,http://www.cnblogs.com/leestar54/p/4105726.html

4, the demo involves a JS closure problem, the free variable recorded in the closure, just a reference to the variable, but not the value of the variable, when the variable is changed, the value of the variable obtained in the closure will also be changed.

See http://www.cnblogs.com/mzwr1982/archive/2012/05/20/2509295.html

Implement

Mainactivity

 PackageCom.example.javascriptinterface;Importjava.util.ArrayList;Importcom.nostra13.universalimageloader.core.DisplayImageOptions;ImportCom.nostra13.universalimageloader.core.ImageLoader;Importcom.nostra13.universalimageloader.core.ImageLoaderConfiguration;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.app.ProgressDialog;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.webkit.WebView;Importandroid.webkit.WebViewClient;ImportAndroid.graphics.Bitmap; Public classMainactivityextendsactionbaractivity {PrivateWebView WebView1; PrivateProgressDialog Pbar; PrivateHandler Mhandler =NewHandler (); @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //initializing the generic picture loaderDisplayimageoptions defaultoptions =NewDisplayimageoptions.builder (). Cacheinmemory (true). Cacheondisk (true). build (); Imageloaderconfiguration Config=NewImageloaderconfiguration.builder ( This). Defaultdisplayimageoptions (defaultoptions). build ();        Imageloader.getinstance (). init (config); Pbar=NewProgressDialog (mainactivity. This); Pbar.settitle (Prompted); Pbar.setmessage ("Loading in ..."); Pbar.setindeterminate (true); WebView1=(WebView) Findviewbyid (R.ID.WEBVIEW1); Webview1.setwebviewclient (Newwebviewclient () {@Override Public voidonpagestarted (WebView view, String URL, Bitmap favicon) {Super. onpagestarted (view, URL, favicon);            Pbar.show (); } @Override Public voidonpagefinished (WebView view, String URL) {Super. onpagefinished (view, URL);                Pbar.dismiss (); //Web page loading complete, weiview into JSAddimageclicklistner ();        }        }); //allow WebView to execute JSWebview1.getsettings (). setjavascriptenabled (true); Webview1.getsettings (). setjavascriptcanopenwindowsautomatically (true); Webview1.loadurl ("Http://news.163.com/jnews/mobile/#detail/99/ai8eshb000964j4o"); //Add the JS interface so that the local function can be called in JS. Webview1.addjavascriptinterface (NewJavascriptinterface ( This),                "Imagelistner"); }     Public classJavascriptinterface {Privatecontext Context;  PublicJavascriptinterface (Context context) { This. Context =context; }        //Be sure to declare that the function is Javascriptinterface@android. Webkit.javascriptinterface Public voidOpenimage (String img,Final intindex) {            FinalString simg =img; Final intFindex =index; Mhandler.post (NewRunnable () {@Override Public voidrun () {string[] IMGs= Simg.split (","); ArrayList<String> Imgsurl =NewArraylist<string>();  for(String s:imgs) {Imgsurl.add (s); } Intent Intent=NewIntent (); Intent.putextra ("Index", Findex);//Current click image indexIntent.putstringarraylistextra ("Infos", Imgsurl);//Image Link ArrayIntent.setclass (context, photosactivity.class);                    Intent.setflags (Intent.flag_activity_new_task);                Context.startactivity (Intent);        }            }); }    }    Private voidAddimageclicklistner () {//The Click Function solves the closure, which is used to display the currently clicked ImageWebview1.loadurl ("javascript: (function () {" + "var objs = document.getElementsByTagName (\" img\ ");"                + "var imgurl= ';"                + "for (Var i=0;i<objs.length;i++)" + "{" + "imgurl+=objs[i].src+ ', ';" + "objs[i].onclick= (function (j) {return function () {window.imagelistner.openImage (imgurl,j);};})  (i); "                + "}" + "} " + ")()"); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//Handle Action Bar item clicks here. The Action Bar would//automatically handle clicks on the Home/up button, so long//As you specify a the parent activity in Androidmanifest.xml.        intID =Item.getitemid (); if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}

It looks like this when you're done.

Demo Address

Link: Http://pan.baidu.com/s/1dDEPPkP Password: 7y6g

WebView between JS and Android native functions

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.