转自http://www.cnblogs.com/lee0oo0/archive/2012/08/01/2617953.html
使用javascript调用android代码
1.使用webview对象的addJavascriptInterface方法
2.addJavascriptInterface方法有两个参数,第一个参数就是我们一般会实现一个自己的类,类里面提供我们要提供给javascript访问的方法;第二个参数是访问我们在obj中声明的方法时候所用到的js对象,调用模式为window.interfaceName.方法名()或者是javascript: interfaceName.方法名() ;,如myWebView.addJavascriptInterface(new JavaScriptinterface(this), "android");
3.编写JavaScriptinterface类,如有一个函数名为showToast()的方法
4.在html中调用时的形式:javascript:android.showToast()。
附上一个小例子:
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 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");
// 把myWebView加载html
myWebView.loadData(htmlText, "text/html", "utf-8");
myWebView.setWebViewClient( new myWebViewClient());
}
// 此按键监听的是返回键,能够返回到上一个网页(通过网页的hostlistery)
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;
}
}
}
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");
// 把myWebView加载html
myWebView.loadData(htmlText, "text/html", "utf-8");
myWebView.setWebViewClient( new myWebViewClient());
}
// 此按键监听的是返回键,能够返回到上一个网页(通过网页的hostlistery)
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"
>
< html xmlns ="http://www.w3.org/1999/xhtml" xml:lang ="zh-CN" dir ="ltr" >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />
< script type ="text/javascript" >
function showAndroidToast(toast) {
javascript:android.showToast(toast);
}
</ script >
</ head >
< body >
< input type ="button" value ="Say hello"
onClick ="showAndroidToast('Hello Android!')" />
</ body >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" xml:lang ="zh-CN" dir ="ltr" >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />
< script type ="text/javascript" >
function showAndroidToast(toast) {
javascript:android.showToast(toast);
}
</ script >
</ head >
< body >
< input type ="button" value ="Say hello"
onClick ="showAndroidToast('Hello Android!')" />
</ body >
</ html >
android的应用程序中,可以直接调用WebView 中的javascript 代码:
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();
// 设置支持javascript
setting.setJavaScriptEnabled( true);
// 增加接口方法,让html页面调用
webView.addJavascriptInterface( new Object(){
// 这里我定义了一个拨打的方法
public void startPhone(String num){
Intent intent= new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
}
}, "demo");
// 加载页面
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('activity传过来的数据')"); // 调用javascript函数
/*
* 通过webView.loadUrl("javascript:xxx")方式就可以调用当前网页中的名称
* 为xxx的javascript方法
*/
}
});
}
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();
// 设置支持javascript
setting.setJavaScriptEnabled( true);
// 增加接口方法,让html页面调用
webView.addJavascriptInterface( new Object(){
// 这里我定义了一个拨打的方法
public void startPhone(String num){
Intent intent= new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
}
}, "demo");
// 加载页面
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('activity传过来的数据')"); // 调用javascript函数
/*
* 通过webView.loadUrl("javascript:xxx")方式就可以调用当前网页中的名称
* 为xxx的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 >
< script type ="text/javascript" >
function show(content){
document.getElementById("countent").innerHTML=
"这是我的javascript调用. 这是:"+content;
}
</ script >
</ head >
< body >
< table align ="center" >
< tr >< td >姓名 </ td >< td >电话 </ td ></ tr >
< tr >< td >小明 </ td >< td >< a href ="javascript:demo.startPhone(123)" >123 </ a ></ td ></ tr >
< tr >< td >小王 </ td >< td >< a href ="javascript:demo.startPhone(456)" >456 </ a ></ td ></ tr >
</ table >
< p id ="countent" >html原始数据 </ p >
</ body >
</ html >
< html >
< head >
< 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=
"这是我的javascript调用. 这是:"+content;
}
</ script >
</ head >
< body >
< table align ="center" >
< tr >< td >姓名 </ td >< td >电话 </ td ></ tr >
< tr >< td >小明 </ td >< td >< a href ="javascript:demo.startPhone(123)" >123 </ a ></ td ></ tr >
< tr >< td >小王 </ td >< td >< a href ="javascript:demo.startPhone(456)" >456 </ a ></ td ></ tr >
</ table >
< p id ="countent" >html原始数据 </ p >
</ body >
</ html >