使用javascript调用android代码

时间:2023-11-24 21:19:56

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()

JavaScriptinterface.java

 1 import android.content.Context;
2 import android.widget.Toast;
3 public class JavaScriptinterface {
4 private Context mContext;
5 /** Instantiate the interface and set the context */
6 public JavaScriptinterface(Context c) {
7 mContext = c;
8 }
9 /** Show a toast from the web page */
10 public void showToast(String toast) {
11 Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
12 }
13 }

MainActivity.java

 1 import java.io.BufferedReader;
2 import java.io.File;
3 import java.io.InputStreamReader;
4 import android.app.Activity;
5 import android.content.Context;
6 import android.os.Bundle;
7 import android.view.KeyEvent;
8 import android.webkit.WebView;
9 import android.webkit.WebViewClient;
10
11 public class MainActivity extends Activity {
12 /** Called when the activity is first created. */
13 private WebView myWebView;
14
15 @Override
16 public void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.main);
19 myWebView = (WebView) findViewById(R.id.myWebView);
20 myWebView.getSettings().setJavaScriptEnabled(true);
21 myWebView.addJavascriptInterface(new JavaScriptinterface(this),
22 "android");
23 String htmlText = getFromAssets("test.html");
24 //把myWebView加载html
25 myWebView.loadData(htmlText, "text/html", "utf-8");
26 myWebView.setWebViewClient(new myWebViewClient());
27
28 }
29 // 此按键监听的是返回键,能够返回到上一个网页(通过网页的hostlistery)
30 public boolean onKeyDown(int keyCode, KeyEvent event) {
31 if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
32 myWebView.goBack();
33 return true;
34 }
35 return super.onKeyDown(keyCode, event);
36 }
37 public String getFromAssets(String fileName) {
38 try {
39 InputStreamReader inputReader = new InputStreamReader(
40 getResources().getAssets().open(fileName));
41 BufferedReader bufReader = new BufferedReader(inputReader);
42 String line = "";
43 String Result = "";
44 while ((line = bufReader.readLine()) != null)
45 Result += line;
46 if (bufReader != null)
47 bufReader.close();
48 if (inputReader != null)
49 inputReader.close();
50 return Result;
51 } catch (Exception e) {
52 e.printStackTrace();
53 }
54 return null;
55 }
56 class myWebViewClient extends WebViewClient {
57 @Override
58 public boolean shouldOverrideUrlLoading(WebView view, String url){
59 view.loadUrl(url);
60 return true;
61 }
62 }
63 }

test.html

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5
6 <script type="text/javascript">
7 function showAndroidToast(toast) {
8 javascript:android.showToast(toast);
9 }
10 </script>
11
12 </head>
13 <body>
14 <input type="button" value="Say hello"
15 onClick="showAndroidToast('Hello Android!')" />
16 </body>
17 </html>

MainActivity02.java

 1 import java.io.BufferedReader;
2 import java.io.File;
3 import java.io.InputStreamReader;
4 import android.app.Activity;
5 import android.content.Context;
6 import android.content.Intent;
7 import android.net.Uri;
8 import android.os.Bundle;
9 import android.os.Handler;
10 import android.view.KeyEvent;
11 import android.view.View;
12 import android.view.View.OnClickListener;
13 import android.webkit.WebSettings;
14 import android.webkit.WebView;
15 import android.webkit.WebViewClient;
16 import android.widget.Button;
17
18 public class MainActivity02 extends Activity {
19 /** Called when the activity is first created. */
20 private WebView webView;
21 private Button button;
22 @Override
23 public void onCreate(Bundle savedInstanceState) {
24 super.onCreate(savedInstanceState);
25 setContentView(R.layout.main2);
26
27 webView=(WebView) this.findViewById(R.id.webView);
28 button=(Button) this.findViewById(R.id.button);
29
30 WebSettings setting=webView.getSettings();
31 //设置支持javascript
32 setting.setJavaScriptEnabled(true);
33 //增加接口方法,让html页面调用
34 webView.addJavascriptInterface(new Object(){
35 //这里我定义了一个拨打的方法
36 public void startPhone(String num){
37 Intent intent=new Intent();
38
39 intent.setAction(Intent.ACTION_CALL);
40 intent.setData(Uri.parse("tel:"+num));
41 startActivity(intent);
42 }
43 }, "demo");
44 //加载页面
45 webView.loadUrl("file:///android_asset/test2.html");
46
47 button.setOnClickListener(new OnClickListener() {
48
49 @Override
50 public void onClick(View v) {
51 // TODO Auto-generated method stub
52 webView.loadUrl("javascript:show('activity传过来的数据')"); //调用javascript函数
53 /*
54 * 通过webView.loadUrl("javascript:xxx")方式就可以调用当前网页中的名称
55 * 为xxx的javascript方法
56 */
57 }
58 });
59 }}

test2.html

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
5 <title>Insert title here</title>
6 <script type="text/javascript">
7 function show(content){
8 document.getElementById("countent").innerHTML=
9 "这是我的javascript调用. 这是:"+content;
10 }
11 </script>
12 </head>
13 <body>
14 <table align="center">
15 <tr><td>姓名</td><td>电话</td></tr>
16 <tr><td>小明</td><td><a href="javascript:demo.startPhone(123)">123</a></td></tr>
17 <tr><td>小王</td><td><a href="javascript:demo.startPhone(456)">456</a></td></tr>
18 </table>
19 <p id="countent">html原始数据</p>
20 </body>
21 </html>

原文链接:http://www.cnblogs.com/lee0oo0/archive/2012/08/01/2617953.html