1:基本使用:
@SuppressWarnings("deprecation") public class ArticleWebView_new extends WebView { private WebSettings wvsetting; public ArticleWebView_new(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub instance(context); } public ArticleWebView_new(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub instance(context); } public ArticleWebView_new(Context context) { super(context); // TODO Auto-generated constructor stub instance(context); } @SuppressLint({ "SetJavaScriptEnabled", "NewApi" }) private void instance(Context context) { // TODO Auto-generated method stub wvsetting = this.getSettings(); // 设置是否允许通过file // url加载的Javascript可以访问其他的源,包括其他的文件和http,https等其他的源。这个设置在JELLY_BEAN以前的版本默认是允许,在JELLY_BEAN及以后的版本中默认是禁止的 try { if (Build.VERSION.SDK_INT >= 16) { Class<?> clazz = this.getSettings().getClass(); Method method = clazz.getMethod( "setAllowUniversalAccessFromFileURLs", boolean.class); if (method != null) { method.invoke(this.getSettings(), true); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 内嵌图片时加载缓慢的问题 if (Build.VERSION.SDK_INT >= 19) { wvsetting.setLoadsImagesAutomatically(true); } else { wvsetting.setLoadsImagesAutomatically(false); } // 屏幕适配滚动问题 wvsetting .setUserAgentString("Mozilla/5.0 (Linux; U; Android 4.4.2; zh-cn;CmsTop Cloud Mobile) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 Safari/537.36"); wvsetting.setJavaScriptEnabled(true);// 支持js wvsetting.setSupportZoom(false); wvsetting.setTextSize(TextSize.NORMAL); // wvsetting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); wvsetting.setAllowFileAccess(true); wvsetting.setDomStorageEnabled(true); wvsetting.setSupportMultipleWindows(true); wvsetting.setPluginState(WebSettings.PluginState.ON); // ws.setPluginsEnabled(true); wvsetting.setLoadWithOverviewMode(true); wvsetting.setUseWideViewPort(true); wvsetting.setDefaultTextEncodingName("utf-8"); wvsetting.setCacheMode(WebSettings.LOAD_NO_CACHE); } }
2:一些常用的监听类型
public class NewsWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // TODO Auto-generated method stub super.onReceivedError(view, errorCode, description, failingUrl); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // TODO Auto-generated method stub super.onReceivedSslError(view, handler, error); handler.proceed(); // 接受所有证书 } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); //是配合图片加载缓存缓慢的问题 if (!view.getSettings().getLoadsImagesAutomatically()) { view.getSettings().setLoadsImagesAutomatically(true); } } }
3:当链接里包含下载地址时:
wv_link.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // TODO Auto-generated method stub Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } });
4:android 5.0之后的兼容问题,部分js加载效果不生效的处理;entity.getResource_url()基类js;直接view_articleWeb.loadDataWithBaseURL(null,detailEntity.getContent(), "text/html", "UTF-8", null);会有部分不兼容的问题
view_articleWeb.loadDataWithBaseURL(entity.getResource_url(), detailEntity.getContent(), "text/html", "UTF-8", null);
5:webview嵌套多层 返回上一层的问题
1:创建数组 private List<String> urlList = new ArrayList<String>(); 2:数据何时添加呢 public class NewsWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("http://") || url.startsWith("https://")) { view.loadUrl(url); urlList.add(url); } return true; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // TODO Auto-generated method stub super.onReceivedSslError(view, handler, error); handler.proceed(); // 接受所有证书 } } 3:怎么返回上一层呢 if (view_articleWeb != null && view_articleWeb.canGoBack()) { if (urlList.size() > 1) { urlList.remove(urlList.size() - 1); view_articleWeb.goBack(); } else { if (urlList.size() == 0) { finishActi(this, animal); } else { urlList.remove(urlList.size() - 1); view_articleWeb.loadDataWithBaseURL(null, detailEntity.getContent(), "text/html", "UTF-8", "about:blank"); } } return; } 4:aty 销毁时记得清空 urlList.clear();
6:页面里嵌套有音视频时,切换页面暂停播放时;这个只要实现在onpause里暂停,onresume里继续就好了 不过这两个方法对应使用才有效
@Override public void onResume() { // TODO Auto-generated method stub super.onTabResumeFragment(); if (wv_link != null) { try { wv_link.getClass().getMethod("onResume") .invoke(wv_link, (Object[]) null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void onPause() { // TODO Auto-generated method stub super.onTabPauseFragment(); if (wv_link != null) { currentTime = (System.currentTimeMillis() / 1000); try { wv_link.getClass().getMethod("onPause") .invoke(wv_link, (Object[]) null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } sackAudioFocus(); } } 上面针对一般般的webview里嵌套视频就没有问题了,但是当有比较low的音频时,也是不好使,所以还有暴力的方法通过抢占资源才可以达到暂停的效果 /** * 抢取音频焦点 */ private void sackAudioFocus() { // TODO Auto-generated method stub if (isHaveAudio) { int i = 0; do { int result = audioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { break; } i++; } while (i < 10); isHaveAudio = false; } }
7:含有音频的webview不要忘记了在配置文件里加上硬件加速 ,否则有声音没画面
<activity android:name=".DetailNewsItemActivity" android:hardwareAccelerated="true" ...... >