Android ---- interactive call between WebView and JavaScript (1)

Source: Internet
Author: User

Nowadays, many mobile apps may embed a web page directly. Benefits: one is convenient feature updates and easy maintenance. You only need to maintain the page of the server without updating the client. The other is universal functionality, not only available for android, ios can also be used, and symbian can also be used directly. In addition, WebView has strong support for Javascript, but it has not been tested by programming. Here is an example to illustrate how to call functions in java in Javascript.

1. Create an android project TestWebView

2. inherited from Activity


[Java]
<Pre name = "code" class = "java" style = "font-family: Arial, Helvetica, simsun, u5b8bu4f53;"> <span style = "font-size: 16px; "> public class TestWebView extends Activity {
Private WebView mWebView;
 
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MWebView = (WebView) findViewById(R.id.html view );
 
WebSettings webSettings = mWebView. getSettings ();

// Whether javascript can be executed in webview
WebSettings. setJavaScriptEnabled (true );
 
// Bind a java object to JavaScript to call a java object in JavaScript for communication.
// The first parameter of this method is the java object, and the second parameter represents the alias of the java object, which is used in JavaScript
MWebView. addJavascriptInterface (new DemoJavaScriptInterface (), "demo ");
 
// Webview loads the local html code. Note that the local html code must be placed in the assets Directory of the project, and then
// File: // android_asset/demo.html
MWebView. loadUrl ("file: // android_asset/demo.html ");
}

Public class DemoJavaScriptInterface {
Public DemoJavaScriptInterface (){
 
}
 
Public int mydata (){
Log. I ("TEST", "mydata .....");
Return 0;
}
}
} </Span>
<Pre name = "code" class = "java" style = "font-family: Arial, Helvetica, simsun, u5b8bu4f53;"> <span style = "font-size: 16px; "> public class TestWebView extends Activity {
Private WebView mWebView;

@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MWebView = (WebView) findViewById(R.id.html view );

WebSettings webSettings = mWebView. getSettings ();

// Whether javascript can be executed in webview
WebSettings. setJavaScriptEnabled (true );

// Bind a java object to JavaScript to call a java object in JavaScript for communication.
// The first parameter of this method is the java object, and the second parameter represents the alias of the java object, which is used in JavaScript
MWebView. addJavascriptInterface (new DemoJavaScriptInterface (), "demo ");

// Webview loads the local html code. Note that the local html code must be placed in the assets Directory of the project, and then
// File: // android_asset/demo.html
MWebView. loadUrl ("file: // android_asset/demo.html ");
}
 
Public class DemoJavaScriptInterface {
Public DemoJavaScriptInterface (){

}

Public int mydata (){
Log. I ("TEST", "mydata .....");
Return 0;
}
}
} </Span>


3. Modify the main. xml file as follows:


[Html]
<Span style = "font-size: 16px;"> <? Xml version = "1.0" encoding = "UTF-8"?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent" android: layout_height = "fill_parent"
>
 
<WebView android: id = "@ + id/htmlview"
Android: layout_centerHorizontal = "true" android: layout_centerVertical = "true"
Android: layout_marginLeft = "0px" android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"/>
 
</RelativeLayout> </span>
<Span style = "font-size: 16px;"> <? Xml version = "1.0" encoding = "UTF-8"?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "fill_parent" android: layout_height = "fill_parent"
>

<WebView android: id = "@ + id/htmlview"
Android: layout_centerHorizontal = "true" android: layout_centerVertical = "true"
Android: layout_marginLeft = "0px" android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"/>

</RelativeLayout> </span>
4. Create an html file: demo.html under the assets Directory and write it using JAVAScript code.


[Javascript]
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Insert title here </title>
</Head>
<Body> this is web html
<Div id = "output"> test </div>
<Input type = "submit" value = "buttons"
Onclick = "document. getElementById ('output'). innerHTML = window. demo. mydata ()"/>
</Body>
</Html>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Insert title here </title>
</Head>
<Body> this is web html
<Div id = "output"> test </div>
<Input type = "submit" value = "buttons"
Onclick = "document. getElementById ('output'). innerHTML = window. demo. mydata ()"/>
</Body>
</Html>

Note the preceding [javascript] view plaincopyprint?
Onclick = "document. getElementById ('output'). innerHTML = window. demo. mydata ()"
Onclick = "document. getElementById ('output'). innerHTML = window. demo. mydata ()"

Directly call window. demo. mydata ()

 


OK. You can easily write the code. Now I will explain the knowledge points used:

First look at the sdk api function introduction:


Public void addJavascriptInterface (Object obj, String interfaceName)


Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.

IMPORTANT:

Using addJavascriptInterface () allows JavaScript to control your application. this can be a very useful feature or a dangerous security issue. when the HTML in the WebView is untrustworthy (for example, part or all of the HTML is provided by some person or process ), then an attacker cocould inject HTML that will execute your code and possibly any code of the attacker's choosing.
Do not use addJavascriptInterface () unless all of the HTML in this WebView was written by you.
The Java object that is bound runs in another thread and not in the thread that it was constructed in.


Parameters
Obj The class instance to bind to JavaScript, null instances are ignored.
InterfaceName The name to used to expose the instance in JavaScript.

 


Using addJavascriptInterface (Object obj, String interfaceName), this method binds a java Object to a javascript Object. The javascript Object Name Is interfaceName (demo) and the scope is Global. After webview initialization, you can directly access the bound java object through javascript: window. demo on the page loaded by webview.

 


In addition, pay attention to the following points during the development process:

1. AndroidManifest. xml must use the permission "android. permission. INTERNET". Otherwise, the Web page not available error may occur.

2. If the accessed page contains Javascript, webview must be set to support Javascript.
Webview. getSettings (). setJavaScriptEnabled (true );

3. If you want to click the link on the page to continue responding in the current browser, instead of making a response in the browser of the new Android system, you must overwrite the WebViewClient object of webview.

MWebView. setWebViewClient (new WebViewClient (){

[Java]
<Span style = "font-size: 16px;"> @ Override
Public boolean shouldOverrideUrlLoading (WebView view, String url ){
View. loadUrl (url );
Return true;
}
}); </Span>
<Span style = "font-size: 16px;"> @ Override
Public boolean shouldOverrideUrlLoading (WebView view, String url ){
View. loadUrl (url );
Return true;
}
}); </Span>

4. If you do not do any processing, browse the Web page and click the system "Back" key. The entire Browser will call finish () to end itself. If you want to roll Back the web page instead of launching the Browser, the Back event needs to be processed and consumed in the current Activity.


[Java]
<Pre name = "code" class = "java" style = "font-family: Arial, Helvetica, simsun, u5b8bu4f53;"> <span style = "font-family: Arial, helvetica, simsun, u5b8bu4f53; "> </span> <pre name =" code "class =" java "> @ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK) & mWebView. canGoBack ()){
MWebView. goBack ();
Return true;
}
Return super. onKeyDown (keyCode, event );
}
<Pre name = "code" class = "java" style = "font-family: Arial, Helvetica, simsun, u5b8bu4f53;"> <span style = "font-family: Arial, helvetica, simsun, u5b8bu4f53; "> </span> <pre name =" code "class =" java "> @ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK) & mWebView. canGoBack ()){
MWebView. goBack ();
Return true;
}
Return super. onKeyDown (keyCode, event );
}
5. the Java object and method to be bound in the addJavascriptInterface method must run in another thread and cannot be run in the Construction thread. This is also the purpose of using Handler. The above code can be modified as follows, and the Handler can be used to send messages for processing:
[Java]
<Span style = "color: rgb (75, 78, 81); line-height: 25px"> <span style = "font-size: 16px "> </span> <pre name =" code "class =" java "> public int mydata (){
MHandler. post (new Runnable (){
Public void run (){
Log. I ("TEST", "mydata .....");
}
});
Return 0;
}

 

 

From andyhuabing's column

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.