0

我正在制作一个使用 WebView 打开某个网页的应用程序。通常,我会手动下载网页并将其放入资产中,然后从那里使用 WebView 打开它,但是该网站包含的信息每月会更改几次,这就是为什么我要使其保持最新的原因。

但是,在保持网站最新的同时,我还希望我的用户能够在离线时访问它。

这就是我希望它的工作方式:

  1. 如果下载的 html 文件在外部存储中尚不存在,请下载
  2. 如果没有互联网连接并且 html 文件存在,则显示该 html 文件
  3. 如果有 Internet 连接并且 html 文件也存在,则显示来自 Internet 的内容并将 html 文件替换为较新的版本

我做了一些研究,我能找到的只是将 WebView 保存在缓存中,但这是不可能的,因为我在 WebView 中打开的网站已禁用缓存(我没有管理权限,我无法联系网站管理员)。

我还对如何使用 webview 下载和显示 html 文件进行了大量研究,但没有任何可以依赖的好例子。

这是我要显示和下载的页面:https ://www.easistent.com/urniki/263/razredi/16515

4

1 回答 1

0

首先检查互联网(您可以在 SO 上找到许多已解决的问题),如果有互联网连接,请使用 HttpClient 获取 HTML 源并将其保存到外部存储。然后在 webview 中从外部存储加载网页。如果没有互联网连接,只需在 webview 中加载页面。

互联网可用时保存和更新 html 源代码:

  HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
  HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
 HttpResponse response = httpclient.execute(httpget); // Executeit
 HttpEntity entity = response.getEntity(); 
 InputStream is = entity.getContent(); // Create an InputStream with the response
  BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) // Read line by line
        sb.append(line + "\n");
    String resString = sb.toString(); // Result is here
     is.close(); // Close the stream
    File file = new File(Environment.getExternalStorageDirectory().toString()+"/Path/to/save/file/index.html");
        file.createNewFile();
        FileOutputStream f1 = new FileOutputStream(file, false);
        PrintStream p = new PrintStream(f1);
        p.print(resString);
        p.close();
        f1.close();

    }catch(IOException e){}

编辑:正如@michaelcarrano 在评论中所说,使用另一个线程在后台执行这项工作。

于 2013-09-08T22:27:18.203 回答