WebView in Android implements Javascript call of Java class methods

Source: Internet
Author: User

To facilitate interaction between webpages and Android applications, the Android system provides a mechanism for JavaScript webpage scripts in WebView to call Java methods. You only need to call the addJavascriptInterface method to map a Java object to a JavaScript Object.
 
1. Map a Java object to a JavaScript Object
 
 
01
<Strong> mWebView = (WebView) findViewById (R. id. wv_content );
02
MWebView. setVerticalScrollbarOverlay (true );
03
Final WebSettings settings = mWebView. getSettings ();
04
Settings. setsuppzoom zoom (true );
05
 
06
// WebView enables Javascript script execution
07
Settings. setJavaScriptEnabled (true );
08
Settings. setJavaScriptCanOpenWindowsAutomatically (true );
09
 
10
// Map the Java object to a Javascript Object named "js2java"
11
// In JavaScript, you can call the Java object method through "window. js2java ".
12
MWebView. addJavascriptInterface (new JSInvokeClass (), "js2java"); </strong>
 
View sourceprint?
1
/** Webpage Javascript call interface **/
2
Class JSInvokeClass {
3
Public void back (){
4
Activity. finish ();
5
}
6
}
2. Example of JavaScript calling Java objects
Call the back method of the preceding JSInvokeClass class object as follows:
 
1
Window. js2java. back ();
 
Author: Dean83

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.