- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- <p>输入数字并提交:</p>
- <input id="id1" type="number">
- <button onclick="myFunction()">提交给android</button>
- <p id="demo"></p>
- <script>
- function myFunction() {
- var inpObj = document.getElementById("id1").value;
- inpObj=inpObj+"";
- window.android.get(inpObj)
- }
- </script>
- </body>
- </html>
android端接受的:
- package com.example.bovenn.jsandroiddemo;
- import android.annotation.SuppressLint;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.webkit.JavascriptInterface;
- import android.webkit.WebSettings;
- import android.webkit.WebView;
- public class MainActivity extends AppCompatActivity {
- @SuppressLint("JavascriptInterface")
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- WebView webView = ((WebView) findViewById(R.id.webView));
- WebSettings webSettings = webView.getSettings();
- webSettings.setJavaScriptEnabled(true);
- webSettings.setDefaultTextEncodingName("utf-8");
- webView.addJavascriptInterface(new JS(), "android");
- webView.loadUrl("file:///android_asset/demo.html");
- }
- class JS{
- @JavascriptInterface
- public void get(String p){
- System.out.println("打印"+p);
- }
- }
- }
再JS 这个类里面的get方法接受网页传递的信息。解释一下:JS 的
- window.android.get(inpObj)
是关键代码其中inpObj必须是String类型。android 这个字和android代码中
- webView.addJavascriptInterface(new JS(), "android");
这儿要对应。window.android.get("传递的值"),中的get要和android中定义JS类里面的get方法名字相同。