android与js的互调

  • H0_915272
    了解作者
  • 98.8KB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-05-27 08:16
    上传日期
这个demo实现了,在java代码中加载js,而在js代码中有调用了java的代码
JavaAndJS.zip
内容介绍
package cn.mifengkong.javaandjs; import android.content.Context; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { private WebView mWebView; private String url = "https://cai-app-h5.huaxiafinance.com:58443/huaxia-crm-h5/authentication/authenticationIndex"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.webview); WebSettings settings = mWebView.getSettings(); //设置WebView属性,能够执行Javascript脚本 settings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new DataJavascriptInterface(this), "onclicklistener"); mWebView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); addImageClickListner(); } }); mWebView.loadUrl(url); } private void addImageClickListner() { //此处的代码是加载js,监听按钮的点击事件,然后获取某些输入框中的内容 mWebView.loadUrl("javascript:(function(){" + "var objs = document.getElementById('authentication'); " + "objs.ontouchend = function()" + " { " + "var mobileNo = document.getElementById('userMobileNo').value; " + "var bankCardNo = document.getElementById('bankCardNo').value; " + "var iDCard = document.getElementById('iDCard').value; " + "var userName = document.getElementById('userName').value; " + "var bankcardName = document.getElementById('bankcardName').options[document.getElementById('bankcardName').selectedIndex].text;" + " window.onclicklistener.savedata(mobileNo,bankCardNo,iDCard,userName,bankcardName);" + " }" + "})()"); } // js通信接口 public class DataJavascriptInterface { private Context context; public DataJavascriptInterface(Context context) { this.context = context; } @JavascriptInterface public void savedata(String mobileNo, String bankCardNo, String iDCard, String userName, String bankcardName) { Log.e("jiang", mobileNo + "--" + bankCardNo + "--" + iDCard + "--" + userName + "--" + bankcardName); } } }
评论
    相关推荐