Android中处理网页时我们必然用到WebView,这里我们有这样一个需求,我们想让WebView在处理网络请求的时候将某些请求拦截替换成某些特殊的资源。具体一点儿说,在WebView加载http://m.sogou.com时,会加载一个logo图片,我们的需求就是将这个logo图片换成另一张图片。

shouldInterceptRequest

好在Android中的WebView比较强大,从API 11(Android 3.0)开始, shouldInterceptRequest被引入就是为了解决这一类的问题。

shouldInterceptRequest这个回调可以通知主程序WebView处理的资源(css,js,image等)请求,并允许主程序进行处理后返回数据。如果主程序返回的数据为null,WebView会自行请求网络加载资源,否则使用主程序提供的数据。注意这个回调发生在非UI线程中,所以进行UI系统相关的操作是不可以的。

shouldInterceptRequest有两种重载。

public WebResourceResponse shouldInterceptRequest (WebView view, String url)从API 11开始引入,API 21弃用

public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)从API 21开始引入

本次例子暂时使用第一种,即shouldInterceptRequest (WebView view, String url)。

示例代码

1234567891011121314151617181920

WebViewwebView=newWebView(this);webView.setWebViewClient(newWebViewClient(){@OverridepublicWebResourceResponseshouldInterceptRequest(WebViewview,Stringurl){Log.i(LOGTAG,"shouldInterceptRequest url="+url+";threadInfo"+Thread.currentThread());WebResourceResponseresponse=null;if(url.contains("logo")){try{InputStreamlocalCopy=getAssets().open("droidyue.png");response=newWebResourceResponse("image/png","UTF-8",localCopy);}catch(IOExceptione){e.printStackTrace();}}returnresponse;}});setContentView(webView);webView.loadUrl("http://m.sogou.com");

其中WebResourceResponse需要设定三个属性,MIME类型,数据编码,数据(InputStream流形式)。


更多相关文章

  1. Android 中LayoutInflater(布局加载器)源码篇之createViewFromTag
  2. Android 使用WebView加载含有echarts的页面,截图不显示的解决方式
  3. Android黑科技动态加载(一)之Java中的ClassLoader
  4. [置顶] Android中View的加载过程
  5. 转---Android Audio System 之一:AudioTrack如何与AudioFlinger交
  6. Android 之采用execSQL和rawQuery方法完成数据的添删改查操作
  7. Android-sharedUserId数据权限 android:sharedUserId

随机推荐

  1. "Kernel version" 中编译时间的前世今生
  2. Unity之调用AndroidWebView
  3. Android中post请求传递json数据给服务端
  4. android视频播放简单实现示例(VideoView&M
  5. Android(安卓)Studio中获取SHA1或MD5的方
  6. Android(安卓)Scroller的用法详解并完成L
  7. Intellij IDEA开发第一个android应用教程
  8. Android中BaseFragment封装多状态视图显
  9. 公钥密码的三大数学问题
  10. android.view.WindowLeaked的解决办法 ha