标签:
1.xml
<?xml version="1.0" encoding="utf-8"?> <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
2.activity
package com.firefly.hybirdapp; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class HomeActivity extends AppCompatActivity { WebView myWebView; // String loadUrl = "file:///android_assets/index.html";本地 String netUrl = "http://172.16.46.114:14023/index.html/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); myWebView = (WebView) findViewById(R.id.webview); myWebView.loadUrl(netUrl);//加载Url //设置WebView myWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); //得到设置类 WebSettings ws = myWebView.getSettings(); ws.setJavaScriptEnabled(true);//允许js脚本 //把js调用的方法写在WebApp myWebView.addJavascriptInterface(new MyWebAppInterface(this), "android"); } //按返回键返回上一页 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Check if the key event was the Back button and if there‘s history if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { myWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } }
3.webApp类
package com.firefly.hybirdapp; import android.content.Context; import android.util.Log; import android.webkit.JavascriptInterface; /** * Created by pengdan on 2016/6/27. */ public class MyWebAppInterface { Context context; public MyWebAppInterface(Context context) { this.context = context; } @JavascriptInterface public String lookData(String data) { Log.e("TAG", data + "hello!!"); //返回信息给html return "hello"; } }
4.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <script src="js/mui.min.js"></script> <link href="css/mui.min.css" rel="stylesheet" /> <script type="text/javascript" charset="utf-8"> mui.init(); function look() { var ua = navigator.userAgent.toLocaleLowerCase(); alert(ua); //判断是否android if (/android/.test(ua)) { //发送消息 var msg = window.android.lookData(‘I am html5‘); //把接收到的消息写到span里面 document.getElementById(‘span‘).innerHTML = msg; alert(msg); } } </script> </head> <body> <h1>彭丹</h1> <button onclick="look()">点击</button> <span id="span"></span> </body> </html>
标签:
原文地址:http://www.cnblogs.com/firefly-pengdan/p/5626228.html