webView 使用指南及使用心得总结

MainActivity

package test.ban.com.webview;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);
        initView();
    }

    private void initView() {
        mWebView = (WebView) findViewById(R.id.wb);
        mWebView.getSettings().setJavaScriptEnabled(true);//支持javascript
        mWebView.requestFocus();//触摸焦点起作用
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//取消滚动条
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置允许js弹出alert对话框
        //load本地
        mWebView.loadUrl("file:///android_asset/hellotest.html");
        //load在线
        //mWebView.loadUrl("http://www.google.com");
        //js访问android,定义接口
        mWebView.addJavascriptInterface(new JsInteration(), "control");
        /**
         * 调用方法例子:window.control.toastMessage(message)
         * js调用Java
         调用格式为window.jsInterfaceName.methodName(parameterValues)
         此例中我们使用的是control作为注入接口名称。
         */
        //设置了Alert才会弹出,重新onJsAlert()方法return true可以自定义处理信息
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //return super.onJsAlert(view, url, message, result);
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
                return true;
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //在当前的webview中跳转到新的url
                view.loadUrl(url);
                //启动手机浏览器来打开新的url
//                Intent i = new Intent(Intent.ACTION_VIEW);
//                i.setData(Uri.parse(url));
//                startActivity(i);
                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);
            }

            //webView默认是不处理https请求的,页面显示空白,需要进行如下设置:
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//如果只是简单的接受所有证书的话,就直接调process()方法就行了
                // handler.cancel();
                // handler.handleMessage(null); } });
            }
        });


    }

    /**
     * android调用js无参无返回值函数
     *
     * @param view
     */
    public void Android2JsNoParmNoResult(View view) {
        final String call = "javascript:sayHello()";
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(call);
            }
        });

    }

    /**
     * android调用js有参无返回值函数
     *
     * @param view
     */
    public void Android2JsHaveParmNoResult(View view) {
        final String call = "javascript:alertMessage(\"" + "我是android传过来的内容,hey man" + "\")";
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(call);
            }
        });
    }

    /**
     * android调用js有参有返回值函数(4.4之前)
     *
     * @param view
     */
    public void Android2JsHaveParmHaveResult(View view) {
        final String call = "javascript:sumToJava(1,2)";
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(call);
            }
        });
    }

    /**
     * android调用js有参有返回值函数(4.4之后)
     * evaluateJavascript方法必须在UI线程(主线程)调用,因此onReceiveValue也执行在主线程
     *
     * @param view
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void Android2JsHaveParmHaveResult2(View view) {
        mWebView.evaluateJavascript("sumToJava2(3,4)", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String Str) {
                Toast.makeText(getApplicationContext(), "我是android调用js方法(4.4后),入参是3和4,js返回结果是" +
                        Str, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 获取网页图片并放大显示
     *
     * @param view
     */
    public void clickPhoto(View view) {
        startActivity(new Intent(this, WithPhotoWebActivity.class));
    }

    /**
     * js调用android的方法
     */
    class JsInteration {
        @JavascriptInterface
        public void toastMessage(String message) {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        }

        @JavascriptInterface
        public void onSumResult(int result) {
            Toast.makeText(getApplicationContext(), "我是android调用js方法(4.4前),入参是1和2,js返回结果是" +
                    result, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 网页回退
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.setVisibility(View.GONE);
            mWebView.removeAllViews();
            mWebView.destroy();
            releaseAllWebViewCallback();
        }
        super.onDestroy();
    }

    /**
     * 防止内存泄露
     */
    public void releaseAllWebViewCallback() {
        if (Build.VERSION.SDK_INT < 16) {
            try {
                Field field = WebView.class.getDeclaredField("mWebViewCore");
                field = field.getType().getDeclaredField("mBrowserFrame");
                field = field.getType().getDeclaredField("sConfigCallback");
                field.setAccessible(true);
                field.set(null, null);
            } catch (NoSuchFieldException e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            } catch (IllegalAccessException e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                Field sConfigCallback = Class.forName("android.webkit.BrowserFrame")
                        .getDeclaredField("sConfigCallback");
                if (sConfigCallback != null) {
                    sConfigCallback.setAccessible(true);
                    sConfigCallback.set(null, null);
                }
            } catch (NoSuchFieldException e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            } catch (ClassNotFoundException e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            } catch (IllegalAccessException e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            }
        }
    }
}


WithPhotoWebActivity

package test.ban.com.webview;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;


/**
 * des:带图片的webview网站
 */
public class WithPhotoWebActivity extends AppCompatActivity {
    private WebView mWebView;
    private ProgressBar pg;
    private String mShareUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_with_photo_webview);
        initView();
    }

    private void initView() {
        pg = (ProgressBar) findViewById(R.id.pg);
        pg.setVisibility(View.VISIBLE);
        mWebView = (WebView) findViewById(R.id.wb);
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        // 启用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 找了个带图片的网站
        mWebView.loadUrl("http://sc.chinaz.com/tupian/beijingtupian.html");
        // 添加js交互接口类,并起别名 imagelistner
        mWebView.addJavascriptInterface(this, "imagelistner");
        mWebView.setWebViewClient(new MyWebViewClient());
        //长按获取图片链接
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                /**
                 * ----如何获取所点击或者所选内容----
                 长按webView上所选内容,可触发OnLongClickListener,
                 以此可以来判断所选内容的类型,来做不同的处理。
                 这类需要了解一下getHitTestResult()函数的使用。
                 int IMAGE_TYPE HitTestResult for hitting an HTML::imgtag
                 int SRC_IMAGE_ANCHOR_TYPE HitTestResult for hitting a HTML::a tagwith src=http +
                 HTML::img
                 */
                WebView.HitTestResult result = mWebView.getHitTestResult();
                if (result != null) {
                    int type = result.getType();
                    if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult
                            .SRC_IMAGE_ANCHOR_TYPE) {
                        String imgurl = result.getExtra();
                        Toast.makeText(WithPhotoWebActivity.this, imgurl, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
                return true;
            }
        });
    }

    // js通信接口
    @JavascriptInterface
    public void openImage(String img) {
        System.out.println(img);
        ShowWebImageActivity.startAction(this, img);
        System.out.println(img);
    }

    // 注入js函数监听
    private void addImageClickListner() {
        // 这段js函数的功能就是,遍历所有的img几点,并添加onclick函数,在还是执行的时候调用本地接口传递url过去
        mWebView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].οnclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
        /**
         this.src
         是img的属性,通过改变img的属性src就可以更换验证码的图片
         */

    }

    // 监听
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //在当前的webview中跳转到新的url
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            view.getSettings().setJavaScriptEnabled(true);
            pg.setVisibility(View.GONE);
            super.onPageFinished(view, url);
            // html加载完成之后,添加监听图片的点击js函数
            addImageClickListner();

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);

            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String
                failingUrl) {

            super.onReceivedError(view, errorCode, description, failingUrl);

        }
    }

    /**
     * 网页回退
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.setVisibility(View.GONE);
            mWebView.removeAllViews();
            mWebView.destroy();
        }
        super.onDestroy();
    }


}


ShowWebImageActivity

package test.ban.com.webview;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

/**
 * des:显示web大图
 */
public class ShowWebImageActivity extends AppCompatActivity {
    private TextView imageTextView = null;
    private ImageView img;
    private String imagePath = null;

    public static void startAction(Context context, String image) {
        Intent intent = new Intent(context, ShowWebImageActivity.class);
        intent.putExtra("image", image);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_show_big_photo);
        this.imagePath = getIntent().getStringExtra("image");

        this.imageTextView = (TextView) findViewById(R.id.tv_url);
        img = (ImageView) findViewById(R.id.img);

        imageTextView.setText(this.imagePath);
        //通过框架Glide把图片显示在imageView上
        Glide.with(this).load(imagePath)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .thumbnail(0.1f).into(img);
    }

}


源码地址:http://download.csdn.net/detail/u010566681/9613298
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值