WebView使用笔记

一、添加权限 允许app访问网络

<manifest ... >
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

 

二、  设置WebViewClient,重写shouldOverrideUrlLoading事件,使用WebView自身加载页面

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    }

设置WebViewClient,打开网页,如果不设置WebViewclient,WebView.loadUrl时会新开一个浏览器开打开。

webView1.setWebViewClient(new MyWebViewClient());
webView1.loadUrl("http://www.baidu.com/");

三 、javascript与Html5交互

1. App端 第一句话的输出一个Andriod的代理到Html dom

webSettings.setJavaScriptEnabled(true);
        webView1.addJavascriptInterface(new WebAppInterface(this), "Android");
新增一个WebAppInterface类
package com.example.myapplication;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

/**
 * Created by 峰 on 2014/10/25.
 */
public class WebAppInterface {
    Context mContext;
    Handler mHandler;
    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
        mHandler = new Handler();
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public int GetLocation() {
        if (mContext != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }
}
 

2. Web端

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Home</title>
</head>
<body>
    <div>
        <input id="Text1" type="text" />
        <br />
        <input id="Button1" type="button" value="button" onclick="showAndroidToast('Hello Android!')" />
        <input id="Button1" type="button" value="button" onclick="GetLocation();" />
    </div>
    <script type="text/javascript">
        function showAndroidToast(toast) {
            Android.showToast(toast);
        }

        function GetLocation()
        {
            var loc = Android.GetLocation();
            document.getElementById("Text1").value = loc;
        }
    </script>
</body>
</html>
posted @ 2014-12-26 21:45  徐某人  阅读(190)  评论(0编辑  收藏  举报