public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btn1; private Button btn2; private WebView mWebView; private EditText name; private Button btn3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); webViewInit(); } private void webViewInit() { WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); // 设置与Js交互的权限 webSettings.setJavaScriptEnabled(true); // 设置允许JS弹窗 mWebView.setWebViewClient(new WebViewClient()); mWebView.setWebChromeClient(new WebChromeClient()); //在js中调用本地java方法 mWebView.addJavascriptInterface(new Object(){ @JavascriptInterface public void showInfoFromJs(String context){ Toast.makeText(MainActivity.this, context, Toast.LENGTH_SHORT).show(); } }, "AndroidWebView"); // //添加客户端支持 mWebView.setWebChromeClient(new WebChromeClient()); mWebView.addJavascriptInterface(new Object(){ @JavascriptInterface //这里我定义了一个拨打的方法 public void callJS3(){ Log.d("MainActivity", "ppppp"); Intent intent=new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:10086")); startActivity(intent); } }, "demo"); // 允许网页缩放 webSettings.setSupportZoom(true); // 把图片加载放在最后来加载渲染 webSettings.setBlockNetworkImage(true); } private void initView() { btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn3 = (Button) findViewById(R.id.btn3); name = (EditText) findViewById(R.id.name); mWebView = (WebView) findViewById(R.id.web); mWebView.loadUrl("file:///android_asset/js.html"); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn1: mWebView.loadUrl("javascript:callJs()"); break; case R.id.btn2: String s= name.getText().toString(); Log.d("MainActivity", s); //mWebView.loadUrl("javascript:callJS1('zhangsnan')"); mWebView.loadUrl("javascript:callJS1('" + s + "')"); break; case R.id.btn3: mWebView.loadUrl("https://weibo.com/"); break; } } }
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript"> function callJs(){ alert("Android调用了JS的callJS方法"); } function callJS1(s){ alert("Android调用了JS的有参"+s); } function callJS2(){ var msg=document.getElementById("put_id").value; AndroidWebView.showInfoFromJs(msg); } </script> </head> <body> <input type="text" value="aa" id="put_id" /> <input type="button" value="Say hello" onClick="callJS2()" /> <a onClick="demo.callJS3()">点击拨打10086</a><br/> </body> </html><uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CALL_PHONE" />