Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2026103
  • 博文数量: 413
  • 博客积分: 10926
  • 博客等级: 上将
  • 技术积分: 3862
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-09 18:14
文章分类

全部博文(413)

文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(6)

2011年(138)

2010年(85)

2009年(42)

2008年(46)

2007年(26)

2006年(59)

分类: 系统运维

2011-12-16 21:30:29

  1. Basic
    • Purpose
      In order to make web app can run offline, W3C HTML5 introduces application cache. The application support this feature called offline web applications,or application cache, or AppCache for short.
    • What's Offline
      • Offline means that app is not in network environment, such as phone is in air-plane mode, or network is disabled, etc.
      • For some browser, such as firefox, offline doesn't mean that target url is not reachable, such as server is down; while others does, such as Chrome, original browser on Android.
    • Diffence between application cache and normal cache
      • Application cache
        • The AppCache will only cache pages which are specifically included in the manifest file
      • Normal cache
        • The normal cache will cache pretty much any page
        • The normal cache is unreliable, as we dont know which pages (and which resources within those pages) will be available for sure.

    • How to work
      The files specified as part of the CACHE: will load from AppCache (not the server) even if you are online, provided that there is no change in the manifest file. If, however, the browser finds an updated manifest file, then the new cache will once again be downloaded according to the what new manifest file says(If app files are modified, but manifest is not updated, new files will not be downloaded. Generally, we add a line '#manifest version 1.0.16' in manifest file, when app files are modified, we can change this line to force app cache to be downloaded atomatically. However, different browser made different implementation, such as for Firefox, after you change html, but don't modify manifest, the html still can be reloaded from server).

  2. Work Flow
    • Create an app to support application cache
      • Create maniest file, such as sample.manifest
        CACHE MANIFEST

        CACHE:
        sample.css
        sample.js
        index.htm

        Note: the postfix of manifest file is arbitrary, but you must configure proper mime-type in next step. ie. if postfix of manifest file is .mymanifest, you must add "AddType text/cache-manifest .mymanifest" to .htaccess
      • Configure Apache server
        1, Make Apache support 'text/cache-manifest' mime-type
        You can use one of the following method
        - in .htaccess
        Add "AddType text/cache-manifest .manifest" to .htaccess in application dir.
        - in mime.types
        text/cache-manifest manifest

      • Linking the HTML file with the manifest file

      • Swap cache once a new one is downloaded
        window.applicationCache.onupdateready = function(e) {
                window.applicationCache.swapCache();
            }

    • Set up Apache server
      • Setup Apache server
      • Configure .htassess
        On Windows:
        1. Open up notepad
        2. Write the contents of your .htaccess
        3. Save as “.htacess”

        On Linux, you can use vi to create .htassess directly
      • Configure AllowOverride (Optional)
        Some guys said 'AllowOverride' must be set to 'ALL' in httpd.conf


  3. Test
    • Test on PC
      You'd beeter to test with Chrome
      • Create test web app
      • Click File > Offline to disable network
    • Test on Android
      • Create souce code
        WebView webview = new WebView(this);

        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        webview.setWebChromeClient(new WebChromeClient()
        {
            @Override
            public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
            {
                  quotaUpdater.updateQuota(spaceNeeded * 2);
                  Toast.makeText(DemoWebviewDumpHtmlActivity.this,
                          "XXXXXXXXXXXXXXXXXXXX", Toast.LENGTH_LONG).show();
            }
         });
               
        webview.getSettings().setDatabasePath("/data/data/com.demo.webview.dump.html/database");
              
        webview.getSettings().setDatabaseEnabled(true); //Must use with webview.getSettings().setDomStorageEnabled(true)
        webview.getSettings().setDomStorageEnabled(true);
             
              
        webview.getSettings().setAppCachePath("/data/data/com.demo.webview.dump.html/cache");  //The path can be arbitiary, but path must exist, and app has write permission to asscess this path. After cached, you can find a file named 'ApplicationCache.db' under that path.
        webview.getSettings().setAppCacheMaxSize(1024*1024*8);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAppCacheEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);

        webview.loadUrl(webUrl);
        setContentView(webview);
      • Set AndroidManifest file

      • Run on Android
      • Make android device into air-plane mode, or disable network, and then launch app again, you will find the web page still can be loaded
      • Change html and manifet on server, and enable network. Then launch app again, you will find the web page is reload from server.

  4. Application cache object in JavaScript 
    • Check to see if offline web app is supported or not
      in JavaScript:
      if (!window.applicationCache)
      {
          //Not supported
          return
      }
    • window.applicationCache.status
      Get current status of applicatioin cache, it can be uncached, idle, checking, downloading etc.
    • events
      such as onchecking, ondownloading, onprogress, etc. ie.
      window.addEventListener("offline", function(e)
      {
              console.log("Application is now offline");
      }, true);
    • window.applicationCache.update()
      This will trigger the application cache download process, which is nearly the same as reloading the page. It simply checks if the manifest has changed, and if so downloads a fresh version of all the content in the cache (respecting any cache headers). Note that even though a new cache is created with this, the page will continue to use the old cache. To make the page use the new cache you have just downloaded, you must use the swapCache() function.

      In Firefox, an exception 'NS_ERROR_DOM_SECURITY_ERR' will be threw out. type "about:config" into your address bar. Then set "security.fileuri.strict_origin_policy" to "false".

      Normally you won’t need to use the update() function, as the browser should automatically do this when reloading a page. Most commonly the swapCache() function will be used in conjunction with the onupdateready event. ie.
      setInterval(function () { window.applicationCache.update(); }, 3600000); // Check for an updated manifest file every 60 minutes. If it's updated, download a new cache as defined by the new manifest file. window.applicationCache.addEventListener('updateready', function(){ // when an updated cache is downloaded and ready to be used window.applicationCache.swapCache(); //swap to the newest version of the cache }, false);

      This code will check for an updated version of the manifest file every 60 minutes. If it finds a different version of the manifest file on the server than it previously encountered, it will download a new cache based on this new manifest. Once that happens, an updateready event will be fired, stating that an updated copy of the cache has finished downloading and is ready to be used. We can then explicitly use the swapCache() function to swap the old cache with the new one we just downloaded.

    • window.applicationCache.swapCache()
      This function tells the browser to start using the new cache data if it is available.

      if you change the manifest file and reload the page, the browser will download the new files in the cache, and then switch to the new cache (as the swapcache() function is called):


         

      ...


  5. Sample

  6. Reference
    • W3C HTML5 AppCache
      http://dev.w3.org/html5/spec/Overview.html#appcache
    • Running your web applications offline with HTML5 AppCache
      http://dev.opera.com/articles/view/offline-applications-html5-appcache/
    • Using HTML5 Application Cache to Create Offline Web Applications

    • Offline Web applications
      http://dev.w3.org/html5/spec/offline.html#offline
    • HTML5 Cache, Android WebView

    • Apache指南: .htaccess文件



阅读(2527) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~