main下新建一个文件assets---www---index.html: 布局加一个webview 然后添加一个网络权限
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hybird</title> <script> function onJsToNative(){ var value=document.getElementById("inputValue").value; alert(value); window.location.href="login://usermanager/userlogin?userName="+value; } function onJsToNative2(){ myApp.showToast("from html show on native !"); } function onNativeToJs(fromNativeValue){ alert(fromNativeValue); } </script> </head> <body> <img src="https://www.baidu.com/img/bd_logo1.png"> <img src="http://img04.sogoucdn.com/app/a/100520024/4edf482718b95060bbdd6b886248296d"> <input id="inputValue"> <button οnclick="onJsToNative()">jsToNative</button> <button οnclick="onJsToNative2()">jsToNative2</button> </body> </html>
MianActivity:
public class MainActivity extends AppCompatActivity { private com.tencent.smtt.sdk.WebView load; // private WebView load; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); } private void initData() { load.loadUrl("file:///android_asset/www/index.html"); WebSettings websetting = load.getSettings(); websetting.setJavaScriptEnabled(true); String ua = websetting.getUserAgentString(); websetting.setUserAgentString(ua+" bwie"); load.setWebChromeClient(new WebChromeClient() { }); load.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("login://") && url.contains("userlogin")) { Uri uri = Uri.parse(url); String userName = uri.getQueryParameter("userName"); showToast(userName); nativeToHTML(); return true; } return super.shouldOverrideUrlLoading(view, url); } }); load.addJavascriptInterface(new MyJavaScriptInter(),"myApp"); } private void initView() { load = (com.tencent.smtt.sdk.WebView) findViewById(R.id.webview_mian_loaddatel); } public void showToast(String str) { Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show(); } class MyJavaScriptInter { @JavascriptInterface public void showToast(String str) { MainActivity.this.showToast(str); } } public void nativeToHTML() { if (Build.VERSION.SDK_INT < 19) { load.loadUrl("javascript:onNativeToJs('from native')"); } else { load.evaluateJavascript("javascript:onNativeToJs('from native')", null); } // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // load.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // } } }