Android webview support HTML5 offline application features detailed configuration

  • 2020-05-07 20:24:37
  • OfStack

HTML5's offline application makes WebApp work even when the network is disconnected, which is a very useful feature. Recently, I also used HTML5 offline application function in my work. Since I did it on Android platform, I naturally chose Webview to parse web pages. But how to make Webivew support the offline application function of HTML5? After trial and error and searching for information on the Internet, the trial and error finally succeeded.

First configure some properties of webview, assuming that activity already has an instance object of Webview named m_webview, and then add the following code:
 
WebSettings webseting = m_webview.getSettings(); 
webseting.setDomStorageEnabled(true); 
webseting.setAppCacheMaxSize(1024*1024*8);// I'm going to set the buffer size 8M 
String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath(); 
webseting.setAppCachePath(appCacheDir); 
webseting.setAllowFileAccess(true); 
webseting.setAppCacheEnabled(true); 
webseting.setCacheMode(WebSettings.LOAD_DEFAULT); 

webview can set up an WebChromeClient object in response to an expanded buffer in its onReachedMaxAppCacheSize function. The following code
 
m_webview.setWebChromeClient(m_chromeClient); 
private WebChromeClient m_chromeClient = new WebChromeClient(){ 
// Expand the capacity of the cache  
@Override 
public void onReachedMaxAppCacheSize(long spaceNeeded, 
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { 
quotaUpdater.updateQuota(spaceNeeded * 2); 
} 
}; 

Next, I need to modify the configuration of http server to support text/ cache-manifest. I used apache server, which is the windows version. I found the mime.types file in conf folder of apache and added it at the end of the file after opening
"text/ cache-manifest mf manifest", restart the server. This step is very important. I failed many times because the server side did not configure this. Finally, I found the clue in the reply of appendix link 1.
After setting Webview above, the offline application of HTML5 can be supported.

Appendix link 1 says the cache directory should be getApplicationContext().getCacheDir().getAbsolutePath(). However, after testing, I found that setting the directory did not work. Maybe the Android version is different, mine is Android 4.0.3, while his is probably the previous Android version.

The cached directory USES getApplicationContext().getDir ("cache", Context.MODE_PRIVATE).getPath () is a clue from appendix link 2.

Related articles: