How Android uses JavaScript to call Android code

Source: Internet
Author: User

Calling Android code using JavaScript

1. Addjavascriptinterface method using the WebView object

The 2.addJavascriptInterface method has two parameters, the first parameter is that we generally implement a class of our own, the class provides the method we want to provide JavaScript access, the second parameter is to access the method we declared in obj when the JS object used , the invocation pattern is window.interfacename. Method name () or Javascript:interfacename. Method name ();, such as Mywebview.addjavascriptinterface (new Javascriptinterface (This), "Android");

3. Write the Javascriptinterface class, such as a method with a function named Showtoast ()

4. Form in HTML when called: Javascript:android.showToast ().
Attach a small example:

Import Android.content.Context;
Import Android.widget.Toast;

public class Javascriptinterface {

Private Context Mcontext;

/** instantiate the interface and set the context */
Public Javascriptinterface (Context c) {
Mcontext = C;
}

/** Show A toast from the Web page */
public void Showtoast (String toast) {
Toast.maketext (Mcontext, Toast, Toast.length_short). Show ();
}
}

Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.InputStreamReader;
Import android.app.Activity;
Import Android.content.Context;
Import Android.os.Bundle;
Import android.view.KeyEvent;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient;

public class Mainactivity extends Activity {
/** called when the activity is first created. */
Private WebView Mywebview;

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

Mywebview = (WebView) Findviewbyid (R.id.mywebview);
Mywebview.getsettings (). Setjavascriptenabled (True);
Mywebview.addjavascriptinterface (New Javascriptinterface (this),
"Android");
String HTMLText = getfromassets ("test.html");
Loading the Mywebview HTML
Mywebview.loaddata (HTMLText, "text/html", "utf-8");
Mywebview.setwebviewclient (New Mywebviewclient ());

}

This key listens for the return key, which can be returned to the previous page (via the Hostlistery of the Web page)
public boolean onKeyDown (int keycode, keyevent event) {
if ((keycode = = keyevent.keycode_back) && mywebview.cangoback ()) {
Mywebview.goback ();
return true;
}
Return Super.onkeydown (KeyCode, event);
}

public string Getfromassets (string fileName) {
try {
InputStreamReader Inputreader = new InputStreamReader (
Getresources (). Getassets (). open (FileName);

BufferedReader bufreader = new BufferedReader (Inputreader);

String line = "";
String Result = "";

while (line = Bufreader.readline ()) = null)
Result + = line;
if (Bufreader! = null)
Bufreader.close ();
if (Inputreader! = null)
Inputreader.close ();
return Result;
} catch (Exception e) {
E.printstacktrace ();
}
return null;
}

Class Mywebviewclient extends Webviewclient {

@Override
public boolean shouldoverrideurlloading (WebView view, String URL) {
TODO auto-generated Method Stub
View.loadurl (URL);
return true;
}

}
}

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>

<script type= "Text/javascript" >
function Showandroidtoast (toast) {
Javascript:android.showToast (toast);
}
</script>

<body>
<input type= "button" value= "Say Hello"
onclick= "Showandroidtoast (' Hello android! ')"/>
</body>



In Android applications, you can call the JavaScript code in WebView directly:

Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.InputStreamReader;
Import android.app.Activity;
Import Android.content.Context;
Import android.content.Intent;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.os.Handler;
Import android.view.KeyEvent;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import android.webkit.WebSettings;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient;
Import Android.widget.Button;

public class MainActivity02 extends Activity {
/** called when the activity is first created. */
Private WebView WebView;
Private button button;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.main2);

webview= (WebView) This.findviewbyid (R.id.webview);
button= (Button) This.findviewbyid (R.id.button);

WebSettings setting=webview.getsettings ();
Setting up JavaScript support
Setting.setjavascriptenabled (TRUE);
Add an interface method to make the HTML page call
Webview.addjavascriptinterface (New Object () {
Here I define a method of dialing
public void Startphone (String num) {
Intent intent=new Intent ();

Intent.setaction (Intent.action_call);
Intent.setdata (Uri.parse ("Tel:" +num));
StartActivity (Intent);
}
}, "demo");
Load page
Webview.loadurl ("file:///android_asset/test2.html");

Button.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Webview.loadurl ("Javascript:show (' data transmitted by activity ')"); Calling JavaScript functions
/*
* The name of the current page can be called by Webview.loadurl ("Javascript:xxx")
* JavaScript method for XXX
*/
}
});
}

}

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<script type= "Text/javascript" >
Function Show (content) {
document.getElementById ("Countent"). innerhtml=
"This is my JavaScript call. This is: "+content;
}
</script>
<body>
<table align= "center" >
<tr><td> name </td><td> phone </td></tr>
<tr><td> Xiao Ming </td><td><a href= "Javascript:demo.startPhone (123)" >123</a></td ></tr>
<tr><td> Xiao Wang </td><td><a href= "Javascript:demo.startPhone (456)" >456</a></td ></tr>
</table>
<p id= "countent" >html raw Data </p>
</body>

How Android uses JavaScript to call Android code

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.