Android与js交互实例
Android 中可以通过webview来实现和js的交互,在程序中调用js代码,只需要将webview控件的支持js的属性设置为true
Android(Java)与JavaScript(HTML)交互有四种情况:
1) Android(Java)调用HTML中js代码
2) Android(Java)调用HTML中js代码(带参数)
3) HTML中js调用Android(Java)代码
4) HTML中js调用Android(Java)代码(带参数)
下面示例总结这四种情况,直接上干货:
1) Android(Java)
private void showWebView(){ // webView与js交互代码 try { mWebView = new WebView(this); setContentView(mWebView); mWebView.requestFocus(); mWebView.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int progress){ JSAndroidActivity.this.setTitle("Loading..."); JSAndroidActivity.this.setProgress(progress); if(progress >= 80) { JSAndroidActivity.this.setTitle("JsAndroid Test"); } } }); mWebView.setOnKeyListener(new View.OnKeyListener() { // webview can go back @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack(); return true; } return false; } }); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDefaultTextEncodingName("utf-8"); mWebView.addJavascriptInterface(getHtmlObject(), "jsObj"); mWebView.loadUrl("http://192.168.1.121:8080/jsandroid/index.html"); } catch (Exception e) { e.printStackTrace(); } } private Object getHtmlObject(){ Object insertObj = new Object(){ public String HtmlcallJava(){ return "Html call Java"; } public String HtmlcallJava2(final String param){ return "Html call Java : " + param; } public void JavacallHtml(){ runOnUiThread(new Runnable() { @Override public void run() { mWebView.loadUrl("javascript: showFromHtml()"); Toast.makeText(JSAndroidActivity.this, "clickBtn", Toast.LENGTH_SHORT).show(); } }); } public void JavacallHtml2(){ runOnUiThread(new Runnable() { @Override public void run() { mWebView.loadUrl("javascript: showFromHtml2('IT-homer blog')"); Toast.makeText(JSAndroidActivity.this, "clickBtn2", Toast.LENGTH_SHORT).show(); } }); } }; return insertObj; }
2) js(HTML)
public void JavacallHtml(){ runOnUiThread(new Runnable() { @Override public void run() { mWebView.loadUrl("javascript: showFromHtml()"); Toast.makeText(JSAndroidActivity.this, "clickBtn", Toast.LENGTH_SHORT).show(); } }); }
相关推荐
88274956 2020-11-03
runner 2020-09-01
梦的天空 2020-08-25
移动开发与培训 2020-08-16
ReunionIsland 2020-08-16
lyqdanang 2020-08-16
MyNameIsXiaoLai 2020-07-08
星辰的笔记 2020-07-04
csstpeixun 2020-06-28
letheashura 2020-06-26
liaoxuewu 2020-06-26
sunzhihaofuture 2020-06-21
FEvivi 2020-06-16
坚持着执着 2020-06-16
waterv 2020-06-14
xiaoge00 2020-06-14
firejq 2020-06-14
firstboy0 2020-06-14
e度空间 2020-06-12
zhongweinan 2020-06-10