Reprint Please specify Source: http://blog.csdn.net/forwardyzk/article/details/46819925
In the work, there is a need to use WebView and JavaScript to interact with, the following we have a simple need to introduce.
First Look at:
Demand:
1. Click on a button to enter an interface to load WebView, assuming that the interface needs to share this interface to other platforms, then display the "Share" button in the current interface, assuming no need to share, then do not show "share" button.
2. On the H5 interface, there is a login button, click Login,
2.1 Assuming that no landing, then the landing interface, after the successful landing, the H5 interface to display the lander.
2.2 Assuming the login, the H5 interface directly displays the current lander.
1. Enable WebView to support JS invocation.
Webview.addjavascriptinterface (New Jshost (Jsactivity.this, Mhandler, WebView), "Jsobject");
The Jshost is a class of its own definition, Jsobject is H5 page calls the Clientjs method of the object (the name is also its own definition, just like the h5javascriprt with the name of the object can be).
2. Share your needs.
When the H5 page is loaded, the H5 page calls the client whether or not to share the method (via this method to share and share content to the client), and then controls whether the share button shows
H5 Page Javascrip Method:
Window.onload = function Share () {//share var json = "{' Isshare ': 0, ' sharecontent ': ' I am sharing content '} ';//Do not share var noshare = ' {' Isshare ': -1} "; Window.jsObject.toShare (JSON);}
This is the JavaScript method that H5 calls the client
Window: object representing the current page
Window.onload indicates that the following method is called after the current H5 page loading is complete
JSON: A JSON string that needs to be shared
Noshare: Represents a JSON string that does not share the amount
Jsobject: is a client-defined JavaScript object
Toshare (JSON): The client's JavaScript method, which allows the client to receive a JSON string. (This is a JSON string that needs to be shared)
Define how JavaScript is shared in the client's Jshost
/** * Shared Method * * @param JSON * /@JavascriptInterface public void Toshare (String json) { LOG.D (TAG, "Web:" + JSON); try { Jsonobject jsonobject = new Jsonobject (JSON); int isshare = Jsonobject.optint ("Isshare"); if (Isshare = = 0) {//indicates the need to share mhandler.sendemptymessage (0); } else if (Isshare = =-1) {//indicates no need to share MHANDLER.S Endemptymessage (1); } } catch (Jsonexception e) { log.d (TAG, "parsing exception"); } }
First you add annotations that identify JavaScript, @JavascriptInerface
Parse the passed JSON string and send a message via the handler object to control whether the share button is displayed
The mhandler is defined in the Jsactivity method, passed to the Jshost class by WebView's set Addjavascriprtinterface method.
Jsactivty corresponding non-bureau documents:
Activity_js.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_ Parent " android:layout_height=" match_parent "> <button android:id=" @+id/btn_share " Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "share"/> <webview android:id= "@+id/webview" android:layout_width= "match_parent" android:layout_height= " Match_parent " android:layout_below=" @id/btn_share "></WebView></RelativeLayout>
Private Handler Mhandler = new Handler () { @Override public void Handlemessage (Message msg) { if (msg.what = = 0) {//Show share btnshare.setvisibility (view.visible);//Show Share button } else if (msg.what = = 1) {//Hide share button Btnshare.setvisibility (View.gone);//Hide Share button } else if (msg.what = = 2) {//Call login Intent Intent = new Intent ( Jsactivity.this, loginactivity.class); Startactivityforresult (Intent, JSACTIVITY.RESULT_OK); } Super.handlemessage (msg); } };
3. Login Requirements
3.1 Click to login, assuming no landing, pop up landing interface
First look at the H5 page click Login, call the client JS method
<input id= "loginName" type= "button" onclick= "IsLogin ()" value= "Login" >
function IsLogin () {var name = Window.jsObject.requestToken ();d Ocument.getelementbyid ("LoginName"). Value = name;}
Click "Login" to invoke the IsLogin () method in JavaScript and call the client's Requesttoken () method in the IsLogin method. ThisRequesttoken () has a return value and the return value is the name of the current login.
The Requesttoken method of client
/** * Request the lander * * @return * * @JavascriptInterface public String requesttoken () { if ( Textutils.isempty (App.getname ())) { mhandler.sendemptymessage (2); } LOG.D (TAG, "Lander name" + "Name=" + app.getname ()); Return Textutils.isempty (App.getname ())? "Not logged in": App.getname (); }
The app operates the login information, has written the login information and read the login information
Assuming that App.getname () obtains the name of the lander, assuming that it is empty, the notification of the login interface is MHANDELR by the method. Returns the current lander to the H5 page at the same time.
Intent Intent = new Intent (jsactivity.this, loginactivity.class); Startactivityforresult (Intent, JSACTIVITY.RESULT_OK);
Use the Startactivityforresult method to open the landing page
Please refer to the usage of Startactivityforresult: click
Check the landing page:
Activity_login.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "Match_parent" android:layout_margintop= "10DP" android:orientation= "vertical" > <Relat Ivelayout android:layout_width= "match_parent" android:layout_height= "50DP" android:gravity= "Center_ve Rtical "android:orientation=" horizontal "> <textview android:id=" @+id/name_des "a Ndroid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_centervertica L= "true" android:text= "Name:"/> <edittext android:id= "@+id/edit_name" Andro Id:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_centervertical= "t Rue "android:layout_torightof=" @id/name_des "/> </RelativeLayout> <relativelayout Android Oid:layout_width= "Match_pareNT "android:layout_height=" 50DP "android:layout_margintop=" 20DP "android:gravity=" center_vertical " android:orientation= "Horizontal" > <textview android:id= "@+id/pass_des" Android:lay Out_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_centervertical= "true" android:text= "pass:"/> <edittext android:id= "@+id/edit_pass" Android:layout_ Width= "Match_parent" android:layout_height= "Wrap_content" android:layout_centervertical= "true" android:layout_torightof= "@id/pass_des"/> </RelativeLayout> <button android:id= "@+id/btn_l Ogin "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layout_margint op= "10DP" android:text= "Login"/></linearlayout>
When you click on Loginbutton, run the login operation
private void Login () { String name = Editname.gettext (). toString (). Trim (); String pass = Editpass.gettext (). toString (). Trim (); if (textutils.isempty (name)) { Toast.maketext (Getapplicationcontext (), "Name is empty", toast.length_short). Show (); return; } else if (Textutils.isempty (pass)) { Toast.maketext (Getapplicationcontext (), "Pass is empty", toast.length_short). Show (); return; } else { App.writelogininfo (name, pass); Setresult (JSACTIVITY.RESULT_OK); Finish (); } }
Once the login is successful, the name and pass are saved in the app.
public class App extends application { private static sharedpreferences sharedpreferences; @Override public void OnCreate () { super.oncreate (); Sharedpreferences = Getapplicationcontext (). Getsharedpreferences ("Login", context.mode_private); public static void Writelogininfo (string name, String pass) { sharedpreferences.edit (). putstring ("name", name). Putstring ("Pass", pass). commit (); } public static String GetName () { return sharedpreferences.getstring ("name", "");} }
At the same time get notifications in the Onactivityresult method in Jsactivity, and then call the Loginsuccess method of the H5 page, passing the login to H5client
@Override protected void onactivityresult (int requestcode, int resultcode, Intent data) { Super.onactivityresult (Requestcode, ResultCode, data); if (Requestcode = = RESULT_OK) { String name = App.getname (); Name = Textutils.isempty (name)?"Not logged in": Name; LOG.D (TAG, "Onactivityresult:" + "name=" + name); Call the Loginsuccess method in the H5 JavaScript webview.loadurl ("javascript:loginsuccess ('" + name + "')"); } }
Webview.loadurl ("Javascript:loginsuccess ('" +name+ ")");
This is how the client calls JavaScript in H5.
function loginsuccess (name) {document.getElementById ("LoginName"). Value = name;}
Name assigns the Value property of the LoginName control to the ID.
Loginsuccess: Is the JavaScript method in H5
Name: is the method parameter
Summarize:
Use WebView's addjavascriprtinterface (Manipulated object, "JavaScript Object name ");
H5 Call the Client method:
No return value: window. JavaScript object. Clientjs method;
There is a return value: var value=window. JavaScript object. Clientjs method;
The client calls the H5 method:
Webview.loadurl ("javascript: Method name (number of references)");
Webview.loadurl ("javascript: Method Name ()");
To this webview and JavaScript methods call each other has been completed, I hope to be helpful to everyone, there are shortcomings to point out.
source code Download: Server and Client source code
WebView interacting with JavaScript--android