Android Application Development-------------WebView (i) WebView and server-side JS interaction

Source: Internet
Author: User


Recently when the company added functionality, some of the features are HTML, which can be displayed in a browser or WebView. Of course we're using the WebView control here.

Benefits of WebApp:

The benefits of nesting the Web in your app there are so few, 1, cross-platform, not only to run on Android, but also to run on iOS, and the absolute unity of style, because it is loaded HTML, with the same set of HTML

2, modified flexible, easy to update the version. For example, we often see the app inside the ads page, mostly nested HTML, so as long as the background to replace the content of the page, the mobile phone will change the presentation, and the new version is the same, because the interface what has become in the server side, so if you want to with the new interface, only need to change in the background in the release, Users are not required to download the app again. This advantage I think to iOS is very helpful, haha, around the apple audit, because HTML we can arbitrarily replace, audit can be the violation of the part of the hidden, on-line can be changed at will, Haha, you know.

Of course, the development of WebApp of course there are limitations, is the speed of anything, this can not be changed, here is not nonsense. But in development, if it's just the interaction between pages, we just need to provide a webview control,

But if it is related to mobile devices or software interaction (such as open album, Camera, etc.), this requires us and the page by the line JS interaction, JS Interaction can be said to be bidirectional, one is, we call the page, is called the service side of the JS method, Another is the server calls our Android code, the call is actually very simple, the following is how to invoke.

Of course we'll wait for a webview first, create an activity, then set the layout, WebView, layout and activity as follows:

Activity_webview.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <webview         android:id= "@+id/webview" android:layout_width= "Match_parent        "        android:layout_height=" match_parent "        /></linearlayout>

And then the activity,

Webviewactivity.activity

Import Android.app.activity;import Android.os.bundle;import Android.webkit.websettings;import Android.webkit.webview;public class Webviewactivity extends Activity {private static final String URL = "http://192.168.3 0.199:8080/song/test.html ";p rivate WebView mwebview; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.LAYOUT.ACTIVITY_WEBVIW); Initview ();} private void Initview () {Mwebview = (WebView) Findviewbyid (R.id.webview);///WebView settingwebsettings settings = Mwebview.getsettings ();//Set support JS, see method name know what meaning settings.setjavascriptenabled (true);//Load page path Mwebview.loadurl (URL);}}

The above is a simple webview, and then the general set of properties, and then load the page path to load, so that the general can be free to click on the page to jump, but to interact with the phone needs we write JS Interactive code.

First of all, how to call the server-side JS method, very simple, and load the page path is basically the same as follows:

Mwebview.loadurl ("Javascript:forsmallphoto ()");

In this simple sentence you can invoke the server-side JS method, where javascript: is fixed notation Forsmallphoto () is the service side of the JS method name, this is a method without parameters, of course, can also be passed, which requires us to cobble together the string, Mwebview.loadurl ("Javascript:forsmallphoto ('" + Data + ")"), where data is a variable, which is the parameter value you want to pass, and of course it can support multi-parameter transfer. This depends on your server side of the JS method has a few parameters, in fact, we call a method, but this method is on the server side. We call the server JS, is to, when the Android to complete certain functions, need to tell the server, then we can call JS to tell him we have finished.

In one thing, the server calls our Android code, and here in Android it's also a good interface.

We can pass void Android.webkit. WebView. Addjavascriptinterface (Object object, String name) method to implement server-side calls to our code, where this method has two parameters, one is object, the other is a string type, and as long as WebView calls this method, it can call our code. and the code to invoke we write in the object, we first implement this object, we create a class, Javascriptinterface. Android API guides provided in the demo to get tired name is Javascriptinterface, then we also use this name. Then implement it, and then write a method in it, like the following

Javascriptinterface.java class

import Java.util.hashmap;import Java.util.map;import Android.content.context;import Android.os.handler;import Android.os.message;import Android.text.textutils;import Android.util.log;import  Android.webkit.javascriptinterface;import android.widget.toast;/** * * Title:JavaScriptInterface.java Description: * * @author Liusong * @version V1.0 */public class Javascriptinterface {/** instantiate the interface and set the context */ Public Javascriptinterface () {}/** Show a toasts from the Web page */@JavascriptInterfacepublic void Showtoast () {log.i ("TA G "," Invoke success ================== "" ");}} 


This completes a simple Javascriptinterface class, this class of method is oneself casually write, in which, first said here to notice several points, first important @javascriptinterface this annotation, you will find to remove also will not error, But this is very early important, if you want to let the server side call your method, you should add this annotation @javascriptinterface. In 4.4api said, must add this annotation, responsible for the call will not succeed, in fact, I in the development, with the red rice 1s,4.3 system, it is impossible to call the success, was also puzzled, because at that time the document is 4.2, is depressed. So be strong here, be sure to add @javascriptinterface in front of your own method of writing.

Another note is the method parameter, here is a non-parametric method, of course, here you can also write a method, here first mention, will be with the HTML inside the JS said, we first said void Android.webkit. WebView. Addjavascriptinterface (Object object, String name) The second parameter inside this method, the second parameter you can understand is the identifier, is the server side call your method, need to find you, how to find? It is through this identifier, the identifier is self-determined, but, you want to tell the background developer what your identifier is, we have this second parameter set to "Android." Now I'm going to show you the HTML code I'm testing and you'll see.

Test.html

<!doctype html>


This code is a bit messy, it will look like this, I put this page on my own Tomcat, which is found in this HTML

<script type= "Text/javascript" >    function callandroidaction (action) {android.showtoast (); alert ("I'm sure You are now using demo one ");    }   function Forsmallphoto (action) {alert ("I'm sure you're using demo one Now" +action);    } </script>


This JS method does not, see the inside of the Android identifier is not, yes, the background is so called our Code, Android.showtoast (); That's what it calls, it's so simple, don't think too hard, we need to do as I said above, the object is implemented, It's OK to write the identifier. After dinner, the backstage will call your method with the identifier and the method name of your object. Here to say, you object (that is, javascriptinterface, we have implemented above) the parameters of the method and the background call your method parameter number and type always, as we normally call method is the same. That's good to know.

That's all you can do.

So add this sentence to the webviewactivity.

View.addjavascriptinterface (New Javascriptinterface (), "Android");

So JS is finished.

Templates

When the background to call our code, we will write a method, if the call to write more than one, so it is too cumbersome, so we write a common method, that is, regardless of the background calls your code to do different things, call you this method, how to distinguish between different execution action? Using the passed parameters, we write a method in Javascriptinterface, here is called callandroidaction, I designed to give this method three parameters,

public void Callandroidaction (string action, String url,string JSON), the first argument action, which is used to represent the action to be performed, and the second is the URL, whether it is the download path to the service or , access to other pages of the path, in a JSON is a few other parameters, because the parameters are not fixed, we use a parameter, a parameter is passed over, multiple parameters can be passed through the JSON string, there is no need to trouble a write parameter.

And then we're designing a callback to get the code out of the operation.

Import Java.util.hashmap;import java.util.map;import Android.content.context;import Android.os.handler;import Android.os.message;import Android.text.textutils;import Android.util.log;import  Android.webkit.javascriptinterface;import android.widget.toast;/** * * Title:JavaScriptInterface.java Description: * * @author Liusong * @version V1.0 */public class Javascriptinterface {private Handler mhandler;/** instantiate the Interfa Ce and set the context */public Javascriptinterface (Handler Handler) {mhandler = Handler;} /** Show A toast from the Web page */@JavascriptInterfacepublic void Showtoast (final String toast) {log.i ("TAG", "call success = = ============== "(" ");} @JavascriptInterfacepublic void Callandroidaction (String action, String url,string JSON) {map<string, string> params = new hashmap<string, string> (); if (! Textutils.isempty (URL)) {params.put ("url", URL);} if (! Textutils.isempty (JSON)) {params.put ("JSON", JSON);} Message msg = Message.obtain (); msg.what = integer.valueof (action); msg.obj = Params;mhandler.sendmessage (msg);}} 


So we're going to give handler the parameters we got from the service, and that's the webviewactivity inside.

Import Java.util.hashmap;import java.util.map;import Android.app.activity;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.webkit.websettings;import Android.webkit.WebView; public class Webviewactivity extends Activity {private static final String URL = "http://192.168.30.199:8080/song/test.ht ML ";//Perform action public static final int select_image = 0;//Open Gallery public static final int open_page = 1;//Jump Other specific page public static F inal int close_or_back = 2;//closed or private WebView mwebview; @Overrideprotected void OnCreate (Bundle savedinstancestate) {su Per.oncreate (savedinstancestate); Setcontentview (R.LAYOUT.ACTIVITY_WEBVIW); Initview ();}  <p> private void Getintentdatas () {  //TODO auto-generated method Stub  url = Getintent (). Getstringextra ("url"),  }</p><p> </p>private void Initview () {MWebView = ( WebView) Findviewbyid (R.id.webview);//or WebView settingwebsettings settings = mwebview.getsettings ();//Set up supportHold JS, look at the method name to know what meaning settings.setjavascriptenabled (true); Mwebview.addjavascriptinterface (New Javascriptinterface ( Handler), "Android");//Load page path Mwebview.loadurl (URL);} Private Handler Handler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {case select_image://execution hit Open the Gallery,//If there are parameters, fetch the parameters passed over the service (Url,json) map<string, string> params = (hashmap<string, string>) msg.obj;break;// Other functions, can be increased with their own functions here, just and the background to negotiate the action of the actions of the value can be default:break;}};};}

Finally let Webviewactivity universal, is by passing URL parameters

private void Getintentdatas () {  //TODO auto-generated method stub  url = Getintent (). Getstringextra ("url");}


That's all you can do.

If you want the demo can leave a message

Android Application Development-------------WebView (i) WebView and server-side JS interaction

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.