在 Cordova/Phonegap for Android 中编写 URL 过滤器

来源:互联网 发布:精功科技 盘古数据 编辑:程序博客网 时间:2024/06/12 18:56
在 Cordova/Phonegap for Android 中编写 URL 过滤器

在《在 Cordova/Phonegap for Android 中调用 API》http://xuekaiyuan.com/forum.php?mod=viewthread&tid=10 只是调用 Cordova/Phonegap提供的默认功能,如果想扩展怎么办?本例中将以编写 URL 过滤器为例讲解一种编写扩展的方法。限于3.0以上版本。

本贴首发于:http://xuekaiyuan.com/forum.php?mod=viewthread&tid=11


创建 URL 过滤器类
创建 com.daonao.test4 包
在包中创建 UrlFilter 类,选择父类为 org.apache.cordova.api.CordovaPlugin

编写 URL 过滤器函数 shouldInterceptRequest
    @Override    @TargetApi(Build.VERSION_CODES.HONEYCOMB)    public WebResourceResponse shouldInterceptRequest(String url) {    ByteArrayInputStream stream = new ByteArrayInputStream(url.getBytes());    return new WebResourceResponse("text/plain", "UTF-8", stream);    }
该过滤器显示输入 URL 的内容,参考该过滤器可以自己设计出各种过滤器。

版本说明
Cordova/Phonegap 的 URL 过滤器插件是对 WebViewClient 中 shouldInterceptRequest 函数的封装。
http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest%28android.webkit.WebView,%20java.lang.String%29
从文档中可以看出,该函数限于 API Lvel 11
http://developer.android.com/gui ... ment.html#ApiLevels
代码为 HONEYCOMB,版本号为 Android 3.0.x,因此该过滤器的函数也限于该版本。
@TargetApi(Build.VERSION_CODES.HONEYCOMB)

编辑 Cordova 的配置文件 config.xml
复制 Cordova 项目中的 res/xml/config.xml 到当前项目的 res/xml/config.xml
直接编辑 config.xml 代码,增加一个 feature 元素
        <feature name="UrlFilter">            <param name="android-package" value="com.daonao.test4.UrlFilter"/>            <url-filter value="file:///android_asset/www/"/>        </feature>

在虚拟机中运行的效果图如下