在 Cordova/Phonegap for Android 中編寫(xiě) URL 過(guò)濾器在《在 Cordova/Phonegap for Android 中調(diào)用 API》http://xuekaiyuan.com/forum.php?mod=viewthread&tid=10 只是調(diào)用 Cordova/Phonegap提供的默認(rèn)功能,如果想擴(kuò)展怎么辦?本例中將以編寫(xiě) URL 過(guò)濾器為例講解一種編寫(xiě)擴(kuò)展的方法。限于3.0以上版本。
本貼首發(fā)于:http://xuekaiyuan.com/forum.php?mod=viewthread&tid=11
創(chuàng)建 URL 過(guò)濾器類(lèi)創(chuàng)建 com.daonao.test4 包
在包中創(chuàng)建 UrlFilter 類(lèi),選擇父類(lèi)為 org.apache.cordova.api.CordovaPlugin
編寫(xiě) URL 過(guò)濾器函數(shù) 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);
- }<em></em>
該過(guò)濾器顯示輸入 URL 的內(nèi)容,參考該過(guò)濾器可以自己設(shè)計(jì)出各種過(guò)濾器。
版本說(shuō)明Cordova/Phonegap 的 URL 過(guò)濾器插件是對(duì) WebViewClient 中 shouldInterceptRequest 函數(shù)的封裝。
http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest%28android.webkit.WebView,%20java.lang.String%29從文檔中可以看出,該函數(shù)限于 API Lvel 11
http://developer.android.com/gui ... ment.html#ApiLevels代碼為 HONEYCOMB,版本號(hào)為 Android 3.0.x,因此該過(guò)濾器的函數(shù)也限于該版本。
- @TargetApi(Build.VERSION_CODES.HONEYCOMB)
編輯 Cordova 的配置文件 config.xml復(fù)制 Cordova 項(xiàng)目中的 res/xml/config.xml 到當(dāng)前項(xiàng)目的 res/xml/config.xml
直接編輯 config.xml 代碼,增加一個(gè) feature 元素
- <feature name="UrlFilter">
- <param name="android-package" value="com.daonao.test4.UrlFilter"/>
- <url-filter value="file:///android_asset/www/"/>
- </feature>
在虛擬機(jī)中運(yùn)行的效果圖如下