Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android WebView 啟用 HTML5 離線應用的完整設定教學

編輯:關於 Android 程式設計

HTML5 離線應用能讓 Web App 在網路中斷時仍可開啟,對 Android 混合應用相當實用。若要在 WebView 中支援離線快取,需要同時設定 DOM Storage、AppCache、快取路徑,並確保伺服器回傳正確的 MIME 類型。

WebView 端基本設定

若 Activity 中已有 WebView 實例,可先取得 WebSettings,再開啟 DOM Storage、AppCache 與檔案存取,並指定應用內的快取目錄。

WebSettings webSettings = m_webview.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
String appCacheDir = getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
webSettings.setAppCachePath(appCacheDir);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

處理快取容量上限

WebView 可透過 WebChromeClient 的 onReachedMaxAppCacheSize 回呼擴充配額,避免快取空間不足。

m_webview.setWebChromeClient(m_chromeClient);
private WebChromeClient m_chromeClient = new WebChromeClient() {
    @Override
    public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
        quotaUpdater.updateQuota(spaceNeeded * 2);
    }
};

伺服器端 MIME 設定

若使用 Apache,需要在 conf 目錄下的 mime.types 加入 text/cache-manifest mf manifest,然後重新啟動伺服器。這一步經常被忽略,卻會直接影響離線快取是否能正常運作。

實測時,getApplicationContext().getCacheDir().getAbsolutePath() 未必能達到預期效果,可改用 getDir("cache", Context.MODE_PRIVATE).getPath() 指定應用私有快取目錄。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved