• JS调JAVA代码


    原文地址:http://droidyue.com/blog/2014/09/20/interaction-between-java-and-javascript-in-android/

    Activiy

    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            final WebView myWebView = (WebView) findViewById(R.id.myWebView);
            WebSettings settings = myWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            myWebView.addJavascriptInterface(new JsInteration(), "control");
            myWebView.setWebChromeClient(new WebChromeClient() {
            });
            myWebView.setWebViewClient(new WebViewClient() {
    
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    testMethod(myWebView);
                }
    
            });
            myWebView.loadUrl("file:///android_asset/js_java_interaction.html");
        }
    
        private void testMethod(WebView webView) {
            String call = "javascript:sayHello()";
    
            //call = "javascript:alertMessage("" + "content" + "")";
    
            call = "javascript:toastMessage("" + "content" + "")";
    
            //call = "javascript:sumToJava(1,2)";
            webView.loadUrl(call);
    
        }
    
        public class JsInteration {
    
            @JavascriptInterface
            public void toastMessage(String message) {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
                        .show();
            }
    
            @JavascriptInterface
            public void onSumResult(int result) {
                //Log.i(LOGTAG, "onSumResult result=" + result);
            }
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    }

    Html代码

    <html>
    <script type="text/javascript">
        function sayHello() {
            alert("Hello")
        }
    
        function alertMessage(message) {
            alert(message)
        }
    
        function toastMessage(message) {
            window.control.toastMessage(message)
        }
    
        function sumToJava(number1, number2){
           window.control.onSumResult(number1 + number2)
        }
    </script>
    Java-Javascript Interaction In Android
    </html>
  • 相关阅读:
    Javascript调用C#后台方法及JSon解析
    ul 仿 table 循环滚动
    windows服务
    simple demo how to get the list of online users
    IIS 4.0配置
    在线
    C学习笔记-多源文件的编译
    C学习笔记-多源文件的编译
    C学习笔记-函数
    C学习笔记-函数
  • 原文地址:https://www.cnblogs.com/a0000/p/4309278.html
Copyright © 2020-2023  润新知