android js 互调

public class BoatsActivity extends Activity {
    Handler mHandler = new Handler();//处理消息的handler
    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("船舶查询页面");
        final WebView mWebView = new WebView(this);//创建一个webView对象出来  将他作为activity的显示页面  你也可以在xml布局文件中放入一个webView控件在这里初始化
        setContentView(mWebView);
        mWebView.loadUrl("http://192.168.0.190:8080/loginDemo_gd/bots.html");//加载你要显示的网页
        mWebView.getSettings().setJavaScriptEnabled(true);//获取webview对象中的setting对象 设置为可以支持javascript
        mWebView.addJavascriptInterface(new Object() { 
            @JavascriptInterface//sdk版本大于17要加上这句注解 访问安全考虑
            public void clickOnAndroid() { 
                mHandler.post(new Runnable() { 
                    public void run() { 
                        Toast.makeText(BoatsActivity.this, "请输入你要查询的船舶", Toast.LENGTH_SHORT).show();
                    } 
                }); 
            }
            @JavascriptInterface
            public void showmsg(){
                mHandler.post(new Runnable() { 
                    public void run() { 
                        Toast.makeText(BoatsActivity.this, "查询成功", Toast.LENGTH_SHORT).show();
                    } 
                }); 
            }
            @JavascriptInterface
            public void showResult(){
                mHandler.post(new Runnable() { 
                    public void run() { 
                        Toast.makeText(BoatsActivity.this, "没有查询到对应的数据", Toast.LENGTH_SHORT).show();
                    } 
                }); 
            }
            @JavascriptInterface
            public void alert(){
                mHandler.post(new Runnable() { 
                    public void run() { 
                        Toast.makeText(BoatsActivity.this, "请输入船舶的ID", Toast.LENGTH_SHORT).show();
                    } 
                }); 
            }
            
        }, "demo");//类的别名  js这样调用  window.demo.方法名(js调用java方法) 

      //java调用js
      webView.loadUrl("javascript:window.handler.show(document.getElementById('id').value,document.getElementById('password').value)");


        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                //Toast.makeText(BoatsActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
                super.onPageFinished(view, url);
            }
        });
    }

}

 

posted @ 2015-09-01 17:55  闻杰  阅读(211)  评论(0编辑  收藏  举报