即使没有网络可用,我如何保存WebView内容?

时间:2011-09-29 13:46:28

标签: android browser android-webview

我正在创建一个应用并使用WebView打开URL。我看到一些应用为用户提供了“保存页面”(网页)选项。

  

我想知道如何从我的WebView保存页面,以便我可以在请求时向用户显示该页面。

1 个答案:

答案 0 :(得分:2)

也许使用缓存是最好的方法......为此你应该检查http://developer.android.com/reference/android/webkit/WebSettings.html

  

“管理WebView的设置状态。当WebView是第一个时   创建后,它会获得一组默认设置。这些默认设置   将从任何getter电话返回。获取WebSettings对象   来自WebView.getSettings()与WebView的生命联系在一起。如果一个   WebView已被破坏,WebSettings上的任何方法调用都将被抛出   一个IllegalStateException。“

Especifically:

public static final int **LOAD_CACHE_ONLY**

自:API级别1 不要使用网络,只从缓存加载。与setCacheMode(int)一起使用。 常数值:3(0x00000003)

或者

public static final int **LOAD_CACHE_ELSE_NETWORK**

自:API级别1 如果有内容,则使用缓存,即使已过期(例如,历史导航)如果它不在缓存中,则从网络加载。与setCacheMode(int)一起使用。 常数值:1(0x00000001)

UPDATE1:

嗯“所有生活中糟糕的代码”,例如:

public static InputStream fetch(String url) throws MalformedURLException,
        IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}


private static String convertStreamToString(InputStream is)
        throws IOException {

    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer, "UTF-8");
    return writer.toString();
}

因此,您可以使用 InputStream fetch(String url)获取网址,然后使用私有静态字符串 convertStreamToString(InputStream is)将该流转换为String并保存流式传输到文件,稍后您可以将该内容加载到webview .....稍后阅读

UPDATE2:

或者你可以做一些Java序列化的东西......不记得这是否适用于android xD

Discover the secrets of the Java Serialization API http://java.sun.com/developer/technicalArticles/Programming/serialization/