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

Source: Internet
Author: User

The previous article mainly explains how to call java functions in js.

Address: http://www.bkjia.com/kf/201205/132839.html

This article uses js and java to call each other to solve the relationship between each other.

 


First, describe the important code:


Key code in android:

Webview. getSettings (). setJavaScriptEnabled (true );

Webview. addJavascriptInterface (object, "name"); // Add the object Name = "name" to the object. If the object is this, It is window. name.

Webview. loadUrl ("file: // android_asset/index.html"); // note that the resource is stored in the assets folder.

 

 

Call the method code in android in js or html:

Use the method () in window. name. java in js ();

The function Method of calling js in android:

Callfunction (){

Webview. loadUrl ("javascript: function ()");

Note that many data types are not recognized in js. It is best to encapsulate them in android to provide necessary method interfaces. For example, if you upload the list to js, you cannot obtain the elements in js.

AddJavascriptInterface: the Java object and method to be bound in the addJavascriptInterface method must run in another thread, and cannot run in the Construction thread, that is, cannot run in the current activity thread, this method is bound to the page. js can also call this method.

Explanation in this document:

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

The Java object that is bound runs in another thread and not in the thread that it was constructed in.

 


The specific test code is provided below:

1. Activity Code


[Java]
Public class TestWebView extends Activity {
Private WebView mWebView;
Private List <String> list;
Private int mkeyCode;
 
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
MWebView = (WebView) findViewById(R.id.html view );
 
InitData ();

WebSettings webSettings = mWebView. getSettings ();

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

MWebView. addJavascriptInterface (this, "javatojs ");
 
// Load the webpage
MWebView. loadUrl ("file: // android_asset/index.html ");
}

@ Override
Public boolean onKeyUp (int keyCode, KeyEvent event ){
MkeyCode = keyCode;
Log. I ("AA", "keyCode =" + keyCode );
MWebView. loadUrl ("javascript: OnKeyUp ()");
Return super. onKeyUp (keyCode, event );
}

Public int getKeyCode (){
Return mkeyCode;
}

Void initData (){
List = new ArrayList <String> ();
For (int I = 0; I <5; I ++ ){
List. add ("I am the nth in List" + (I + 1) + "row ");
}
}

/**
* This method will be called in the js script through window. javatojs... ().
*
* @ Return
*/
Public Object getObject (int index ){
Log. I ("A", "getObject ");
Return list. get (index );
}
 
Public int getSize (){
Log. I ("A", "getSize ");
Return list. size ();
}
 
Public void Callfunction (){
Log. I ("A", "Callfunction ");
MWebView. loadUrl ("javascript: GetList ()");
}

Public void printStr (String str ){
Log. I ("A", "GetList:" + str );
}
}
Public class TestWebView extends Activity {
Private WebView mWebView;
Private List <String> list;
Private int mkeyCode;

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

InitData ();

WebSettings webSettings = mWebView. getSettings ();

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

MWebView. addJavascriptInterface (this, "javatojs ");

// Load the webpage
MWebView. loadUrl ("file: // android_asset/index.html ");
}
 
@ Override
Public boolean onKeyUp (int keyCode, KeyEvent event ){
MkeyCode = keyCode;
Log. I ("AA", "keyCode =" + keyCode );
MWebView. loadUrl ("javascript: OnKeyUp ()");
Return super. onKeyUp (keyCode, event );
}
 
Public int getKeyCode (){
Return mkeyCode;
}
 
Void initData (){
List = new ArrayList <String> ();
For (int I = 0; I <5; I ++ ){
List. add ("I am the nth in List" + (I + 1) + "row ");
}
}
 
/**
* This method will be called in the js script through window. javatojs... ().
*
* @ Return
*/
Public Object getObject (int index ){
Log. I ("A", "getObject ");
Return list. get (index );
}

Public int getSize (){
Log. I ("A", "getSize ");
Return list. size ();
}

Public void Callfunction (){
Log. I ("A", "Callfunction ");
MWebView. loadUrl ("javascript: GetList ()");
}
 
Public void printStr (String str ){
Log. I ("A", "GetList:" + str );
}
}
2. js Code index.html


[Javascript]
<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<Html>
 
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
 
<Title> demotitle> </title>
 
<Script language = "javascript">
 
Function GetList (){
Var I = window. javatojs. getSize ();
 
For (var n = 0; n <I; n ++ ){
Var jsdata = window. javatojs. getObject (n); // obtain the property javadata in the activity.
Window. javatojs. printStr ("test ");
}
}
 
Function OnKeyUp (){
Var keycode = window. javatojs. getKeyCode ();
Window. javatojs. printStr (keycode );
}
 
</Script>
</Head>
 
<Body style = "background-color: #000;">
<Table width = "400" align = "center"> <tr> <td>
<P> </p>
<P>
<Table width = "400" align = "center">
<Div id = "output"> test </div>
<Input type = "submit" value = "buttons"
Onclick = "document. getElementById ('output'). innerHTML = window. javatojs. Callfunction ()"/>
<Br>
 
</P>
</Td> </tr> </table>
</Body>
 
</Html>
<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN">
<Html>

<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">

<Title> demotitle> </title>

<Script language = "javascript">

Function GetList (){
Var I = window. javatojs. getSize ();

For (var n = 0; n <I; n ++ ){
Var jsdata = window. javatojs. getObject (n); // obtain the property javadata in the activity.
Window. javatojs. printStr ("test ");
}
}

Function OnKeyUp (){
Var keycode = window. javatojs. getKeyCode ();
Window. javatojs. printStr (keycode );
}

</Script>
</Head>

<Body style = "background-color: #000;">
<Table width = "400" align = "center"> <tr> <td>
<P> </p>
<P>
<Table width = "400" align = "center">
<Div id = "output"> test </div>
<Input type = "submit" value = "buttons"
Onclick = "document. getElementById ('output'). innerHTML = window. javatojs. Callfunction ()"/>
<Br>

</P>
</Td> </tr> </table>
</Body>

</Html>

The above code mainly tests the mutual calls between js and java. webview intercepts the system event such as buttons, which can be handled in the following two ways:

1. Change the direction key process to: pass it to webcore first. If it is not processed, then it will be processed in webview. This requires modifying the webview. java code.

2. apply it directly. Capture the buttons in java and call the js function. The above Code uses this method.

 


The test result is as follows: Click the buttons button:

I/A (4990): Callfunction

I/A (4990): getSize

I/A (4990): getObject

(I/A (4990): GetList: test)

I/A (4990): getObject

(I/A (4990): GetList: test)

I/A (4990): getObject

(I/A (4990): GetList: test)

I/A (4990): getObject

(I/A (4990): GetList: test)

I/A (4990): getObject

(I/A (4990): GetList: test)

 


You press KEY_RIGHT

I/AA (4990): keyCode = 22

I/A (4990): GetList: 22

 


You press KEY_UP

I/AA (4990): keyCode = 19

I/A (4990): GetList: 19

 


You press KEY_DOWN

I/AA (4990): keyCode = 20

I/A (4990): GetList: 20

 


You press KEY_LEFT

I/AA (4990): keyCode = 21

I/A (4990): GetList: 21


The reason why this method is used is that webview intercepts the function key from top to bottom, left, right, and left, and cannot be passed to webcore. Instead, the OnKeyDown/OnKeyUp method can only be reloaded, it is obtained by js calling the java method.

You can directly process the number key in js:

There will be obvious printing in logcat, and these keys are not truncated, so you can get them directly:

D/webcore (4990): proc key: code = 12

D/webcore (4990): proc key: nativeKey return false

D/webcore (4990): proc key: nativeKey return true

Js Code can be written as follows:


[Javascript]
<Script language = "JavaScript">
 
Document. onkeypress = grab_keypress_event;
Document. onirkeypress = grab_irkeypress_event;
Document. onsystemevent = grab_system_event;
Document. onkeydown = grab_keydown_event;
Document. onkeyup = grab_keyup_event;
 
Function init ()
{
Document. getElementById ("txt_keypress"). innerHTML = "";
Document. getElementById ("txt_irkey"). innerHTML = "";
Document. getElementById ("txt_systemevent"). innerHTML = "";
Document. getElementById ("txt_keydown"). innerHTML = "";
Document. getElementById ("txt_keyup"). innerHTML = "";
}
 
Function grab_keypress_event (event)
{
Var keycode = event. keyCode;
Document. getElementById ("txt_keypress"). innerHTML = keycode;
}
 
Function grab_irkeypress_event (event)
{
Var keycode = event. keyCode;
Document. getElementById ("txt_irkey"). innerHTML = keycode;
}
 
Function grab_system_event (event)
{
Var keycode = event. which;
Document. getElementById ("txt_systemevent"). innerHTML = keycode;
}
 
Function grab_keydown_event (event)
{
Var keycode = event. keyCode;
Var type = event. type;
Var mod = event. modifiers;
Document. getElementById ("txt_keydown"). innerHTML = keycode;
}
 
Function grab_keyup_event (event)
{
Var keycode = event. keyCode;
Document. getElementById ("txt_keyup"). innerHTML = keycode;
}
</Script>
<Script language = "JavaScript">

Document. onkeypress = grab_keypress_event;
Document. onirkeypress = grab_irkeypress_event;
Document. onsystemevent = grab_system_event;
Document. onkeydown = grab_keydown_event;
Document. onkeyup = grab_keyup_event;
 
Function init ()
{
Document. getElementById ("txt_keypress"). innerHTML = "";
Document. getElementById ("txt_irkey"). innerHTML = "";
Document. getElementById ("txt_systemevent"). innerHTML = "";
Document. getElementById ("txt_keydown"). innerHTML = "";
Document. getElementById ("txt_keyup"). innerHTML = "";
}
 
Function grab_keypress_event (event)
{
Var keycode = event. keyCode;
Document. getElementById ("txt_keypress"). innerHTML = keycode;
}

Function grab_irkeypress_event (event)
{
Var keycode = event. keyCode;
Document. getElementById ("txt_irkey"). innerHTML = keycode;
}

Function grab_system_event (event)
{
Var keycode = event. which;
Document. getElementById ("txt_systemevent"). innerHTML = keycode;
}

Function grab_keydown_event (event)
{
Var keycode = event. keyCode;
Var type = event. type;
Var mod = event. modifiers;
Document. getElementById ("txt_keydown"). innerHTML = keycode;
}

Function grab_keyup_event (event)
{
Var keycode = event. keyCode;
Document. getElementById ("txt_keyup"). innerHTML = keycode;
}
</Script>

 


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.