使用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()
。
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