loadData和loadDataWithBaseUrl

在寫WebView時,感覺LoadUrl太浪費流量,而且加載起來有點慢,就考慮用其它的方法來實現。在加載頁面時,如果只加載數據,頁面模板提前寫好放到項目中,這樣就可以來更快的加載頁面,用戶體驗會好些。

      如果不用loadUrl,省下的就只有LoadData和loadDataWithBaseURL了,下面來說下LoadData和loadDataWithBaseURL 的用法;

      loadData:

public void loadData (String data, String mimeType, String encoding)

Load the given data into the WebView. This will load the data into WebView using the data: scheme. Content loaded through this mechanism does not have the ability to load content from the network.

Parameters
datamimeTypeencoding
A String of data in the given encoding. The date must be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
The MIMEType of the data. i.e. text/html, image/jpeg
The encoding of the data. i.e. utf-8, base64

下如API中所說的,

      data:是要加載的數據類型,但在數據裏面不能出現英文字符:'#', '%', '\' , '?' 這四個字符,如果有的話可以用 %23, %25, %27, %3f,這些字符來替換,在平時測試時,你的數據時,你的數據裏含有這些字符,但不會出問題,當出問題時,你可以替換下。

       %,會報找不到頁面錯誤,頁面全是亂碼。亂碼樣式見符件。

       #,會讓你的goBack失效,但canGoBAck是可以使用的。於是就會產生返回按鈕生效,但不能返回的情況。

       \ 和? 我在轉換時,會報錯,因爲它會把\當作轉義符來使用,如果用兩級轉義,也不生效,我是對它無語了。

我們在使用loadData時,就意味着需要把所有的非法字符全部轉換掉,這樣就會給運行速度帶來很大的影響,因爲在使用時,在頁面stytle中會使用很多%號。頁面的數據越多,運行的速度就會越慢。

      data中,有人會遇到中文亂碼問題,解決辦法:參數傳"utf-8",頁面的編碼格式也必須是utf-8,這樣編碼統一就不會亂了。別的編碼我也沒有試過。

 

public

 
void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)

Load the given data into the WebView, use the provided URL as the base URL for the content. The base URL is the URL that represents the page that is loaded through this interface. As such, it is used to resolve any relative URLs. The historyUrl is used for the history entry.

Note for post 1.0. Due to the change in the WebKit, the access to asset files through "file:///android_asset/" for the sub resources is more restricted. If you provide null or empty string as baseUrl, you won't be able to access asset files. If the baseUrl is anything other than http(s)/ftp(s)/about/javascript as scheme, you can access asset files for sub resources.

Parameters
baseUrldatamimeTypeencodinghistoryUrl
Url to resolve relative paths with, if null defaults to "about:blank"
A String of data in the given encoding.
The MIMEType of the data. i.e. text/html. If null, defaults to "text/html"
The encoding of the data. i.e. utf-8, us-ascii
URL to use as the history entry. Can be null.

 

在使用loadDataWithBaseURL時,需要注意的就是 baseUr:雖然API上寫的是要傳一個Url,但我在用時,發現傳一個Url並不可以,我發現這個就是一個標誌位,用來標誌當前頁面的Key值的,而historyUrl就是一個value值,在加載時,它會把baseUrl和historyUrl傳到List列表中,當作歷史記錄來使用,當前進和後退時,它會通過baseUrl來尋找historyUrl的路徑來加載historyUrl路徑來加載歷史界面,需要注意的就是history所指向的必須是一個頁面,並且頁面存在於SD卡中或程序中(assets),loadDataWithBaseURL,它本身並不會向歷史記錄中存儲數據,要想實現歷史記錄,需要我們自己來實現,也許是我的技術有限,我有了比較笨的訪求來實現:就是在加載頁面時,我把數據另外的寫到一個html頁面中,並把它保存到SD中,當點擊返回時,它會通過historyUrl指向的路徑來加載頁面,這樣就解決了歷史記錄問題。

 

上面這兩種方法,我建議使用後者,雖然loadData的歷史記錄不需要我們自己來實現,但在使用時,我們必須把所有的%,#,\,?轉換掉,在轉換時,也許會遇到別的困難,我也沒有測完。這就兩個加載上後者比前者快一到兩倍。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章