Android-webview for offline cache reading

Source: Internet
Author: User
Tags deprecated root access

Objective

This blog to achieve is an offline download and offline reading function, which is a lot of reading app is a common feature, the typical application is NetEase news. What is offline download? In fact, this concept is relatively vague, is offline after downloading it, or after downloading offline, but a little bit of brain people know how to download after the network? So offline download this feature is " in the case of a network, download resources to local ", offline reading is " in the absence of network or network bad, read the local good cache of the article Resources ." This makes it clear that we need both of these specific functional requirements.

Implementation ideas

Little Witch. Here are two implementation ideas, one is to write their own logic, one is through the webview itself with the cache function to achieve. First idea:

  1. Define an offline download of service services
  2. Start the background Services service to perform an asynchronous download
  3. stored in a local database
  4. Each time the URL is loaded, determine whether the database has cached content 5. If there is a cache, the local cache is loaded first, and if it does not exist, the networking request is executed

The second idea is what this blog is about to do offline reading through WebView's own caching function. Here's an example of a blog post where you can add code.

Reference 1:http://www.open-open.com/lib/view/open1392188052301.html Reference 2:http://87426628.blog.163.com/blog/static/ 6069361820139183417725/

The

Android WebView cache can be divided into page cache and data cache page caching refers to the HTML, JS, CSS and other pages or resource data when loading a Web page. Data caches are two types: AppCache and Dom Storage (Web Storage). AppCache is also our H5 cache, we can set the cached directory Dom storage has session storage and local storage two kinds, the former is conversation-level storage, the page closes and disappears, the latter is localized storage. If we have root access to the phone, we can see the file directory under/data/data/package_name/, we will find webview for us to create App_webview, this should be the location of the WebView cache directory.

public void initWebView() {    mWebView.getSettings().setJavaScriptEnabled(true);    mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);    // 建议缓存策略为,判断是否有网络,有的话,使用LOAD_DEFAULT,无网络时,使用LOAD_CACHE_ELSE_NETWORK    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 设置缓存模式    // 开启DOM storage API 功能    mWebView.getSettings().setDomStorageEnabled(true);    // 开启database storage API功能    mWebView.getSettings().setDatabaseEnabled(true);    String cacheDirPath = getFilesDir().getAbsolutePath()            + APP_CACHE_DIRNAME;    Log.i("cachePath", cacheDirPath);    // 设置数据库缓存路径    mWebView.getSettings().setDatabasePath(cacheDirPath); // API 19 deprecated    // 设置Application caches缓存目录    mWebView.getSettings().setAppCachePath(cacheDirPath);    // 开启Application Cache功能    mWebView.getSettings().setAppCacheEnabled(true);    Log.i("databasepath", mWebView.getSettings().getDatabasePath());}

Here to load an article in my blog:

public void Findview () {Initwebview (); Mwebview.setwebviewclient (New Webviewclient () {@Override public void Onloadresource (WebView view, String ur            L) {log.i (TAG, "onloadresource url=" + URL);        Super.onloadresource (view, URL); } @Override public Boolean shouldoverrideurlloading (WebView view, String URL) {log.i (TAG, "Inter            cept url= "+ URL);            View.loadurl (URL);        return true;            }//@Override public void onpagestarted (WebView view, String URL, Bitmap favicon) is called at the beginning of the page {            LOG.E (TAG, "onpagestarted");        super.onpagestarted (view, URL, favicon); }//Page load complete call @Override public void onpagefinished (WebView view, String URL) {Super.onpag        efinished (view, URL); } @Override public void Onreceivederror (WebView view, int errorCode, String description, Stri ng Failingurl) {Super.onReceivederror (view, ErrorCode, description, Failingurl);        Toast.maketext (Getapplicationcontext (), "", Toast.length_long). Show ();    }    }); Mwebview.setwebchromeclient (New Webchromeclient () {@Override public boolean onjsalert (WebView view, String            URL, String message, jsresult result) {LOG.E (TAG, "Onjsalert" + message);            Toast.maketext (Getapplicationcontext (), message, Toast.length_short). Show ();            Result.confirm ();        Return Super.onjsalert (view, URL, message, result); } @Override public Boolean onjsconfirm (WebView view, string URL, String message, Jsresult res            Ult) {LOG.E (TAG, "onjsconfirm" + message);        Return super.onjsconfirm (view, URL, message, result); @Override public boolean onjsprompt (WebView view, string URL, String message, String Defaul TValue, JspromptresuLt result) {log.e (TAG, "onjsprompt" + URL);        Return super.onjsprompt (view, URL, message, defaultvalue, result);    }    }); Mwebview.loadurl (URL);}
Full code
package com.infzm.webview;

Import Java.io.File;

Import android.app.Activity; Import android.content.Intent; Import Android.graphics.Bitmap; Import Android.net.Uri; Import Android.os.Bundle; Import Android.util.Log; Import android.view.KeyEvent; Import Android.view.View; Import Android.view.View.OnClickListener; Import Android.webkit.JsPromptResult; Import Android.webkit.JsResult; Import android.webkit.WebChromeClient; Import android.webkit.WebSettings; Import android.webkit.WebSettings.RenderPriority; Import Android.webkit.WebView; Import android.webkit.WebViewClient; Import Android.widget.Button; Import Android.widget.Toast;

public class Mainactivity extends Activity implements Onclicklistener {

Private WebView mwebview;private button nightmodebtn;private button lightmodebtn;//-----private static final String TAG = MainActivity.class.getSimpleName ();p rivate static final String app_cache_dirname = "/webcache"; Web cache directory private String URL;    Page url@overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main);    Mwebview = (WebView) This.findviewbyid (R.id.webview);    NIGHTMODEBTN = (Button) This.findviewbyid (R.id.btn_nightmode);    LIGHTMODEBTN = (Button) This.findviewbyid (R.id.btn_lightmode);    Nightmodebtn.setonclicklistener (this);    Lightmodebtn.setonclicklistener (this);    Webview.loadurl ("http://www.baidu.com");    WebSettings settings = Mwebview.getsettings ();    Set JavaScript available settings.setjavascriptenabled (true); Binding JavaScript interface, can be implemented in JavaScript call our Android code//Webview.addjavascriptinterface (new Webappinterface (this), "    Android "); Webview.setwebviewclient (New MyWebViewclient ());    Load HTML page in assets directory//Mwebview.loadurl ("file:///android_asset/01.html");    url = "http://blog.csdn.net/wwj_748/article/details/44810283"; Findview ();}    public void Findview () {Initwebview (); Mwebview.setwebviewclient (New Webviewclient () {@Override public void Onloadresource (WebView view, String ur            L) {log.i (TAG, "onloadresource url=" + URL);        Super.onloadresource (view, URL); } @Override public Boolean shouldoverrideurlloading (WebView view, String URL) {log.i (TAG, "Inter            cept url= "+ URL);            View.loadurl (URL);        return true;            }//@Override public void onpagestarted (WebView view, String URL, Bitmap favicon) is called at the beginning of the page {            LOG.E (TAG, "onpagestarted");        super.onpagestarted (view, URL, favicon); }//Page load complete call @Override public void onpagefinished (WebView view, String URL) {Super.onpag Efinished(view, URL); } @Override public void Onreceivederror (WebView view, int errorCode, String description, Stri            ng Failingurl) {super.onreceivederror (view, ErrorCode, description, Failingurl);        Toast.maketext (Getapplicationcontext (), "", Toast.length_long). Show ();    }    }); Mwebview.setwebchromeclient (New Webchromeclient () {@Override public boolean onjsalert (WebView view, String            URL, String message, jsresult result) {LOG.E (TAG, "Onjsalert" + message);            Toast.maketext (Getapplicationcontext (), message, Toast.length_short). Show ();            Result.confirm ();        Return Super.onjsalert (view, URL, message, result); } @Override public Boolean onjsconfirm (WebView view, string URL, String message, Jsresult res            Ult) {LOG.E (TAG, "onjsconfirm" + message); Return Super.onjsconfirm (View, URL, message, result); @Override public boolean onjsprompt (WebView view, string URL, String message, String Defaul            TValue, jspromptresult result) {LOG.E (TAG, "onjsprompt" + URL);        Return super.onjsprompt (view, URL, message, defaultvalue, result);    }    }); Mwebview.loadurl (URL);}    public void Initwebview () {mwebview.getsettings (). Setjavascriptenabled (True);    Mwebview.getsettings (). setrenderpriority (Renderpriority.high); The recommended cache policy is to determine if there is a network, if any, using Load_default, without network, use Load_cache_else_network mwebview.getsettings (). Setcachemode ( Websettings.load_cache_else_network);    Set cache mode//Turn on DOM storage API function Mwebview.getsettings (). Setdomstorageenabled (True);    Open the Database Storage API function Mwebview.getsettings (). Setdatabaseenabled (True);    String Cachedirpath = Getfilesdir (). GetAbsolutePath () + app_cache_dirname;    LOG.I ("CachePath", Cachedirpath); Set the database cache path MWEBVIEW.GEtsettings (). SetDatabasePath (Cachedirpath);    API deprecated//Set application caches cache directory Mwebview.getsettings (). Setappcachepath (Cachedirpath);    Turn on the application cache function mwebview.getsettings (). Setappcacheenabled (True); LOG.I ("DatabasePath", Mwebview.getsettings (). Getdatabasepath ());}        public void Clearwebviewcache () {//clean WebView Cache database try {deletedatabase ("webview.db");    DeleteDatabase ("webviewcache.db");    } catch (Exception e) {e.printstacktrace ();    }//WebView cache file Appcachedir = new file (Getfilesdir (). GetAbsolutePath () + app_cache_dirname);    LOG.E (TAG, "Appcachedir path=" + Appcachedir.getabsolutepath ());    File Webviewcachedir = new file (Getcachedir (). GetAbsolutePath () + "/webviewcache");    LOG.E (TAG, "Appcachedir path=" + Webviewcachedir.getabsolutepath ());    Delete the WebView cache directory if (webviewcachedir.exists ()) {DeleteFile (webviewcachedir); }//delete WebView cache, cache directory if (appcachedir.exists()) {DeleteFile (appcachedir);    }}public void DeleteFile (file file) {log.i (TAG, "delete file path=" + File.getabsolutepath ());        if (file.exists ()) {if (File.isfile ()) {file.delete ();            } else if (File.isdirectory ()) {file files[] = File.listfiles ();            for (int i = 0; i < files.length; i++) {DeleteFile (files[i]);    }} file.delete ();    } else {log.e (TAG, "delete file no exists" + file.getabsolutepath ()); }}/** * for controlling page navigation * * @author wwj_748 * */private class Mywebviewclient extends Webviewclient {/** * when used to click on a link, system call This method */@Override public boolean shouldoverrideurlloading (WebView view, String URL) {if (Uri.parse (URL)).        GetHost (). Equals ("www.baidu.com") {//This is my page, so do not overwrite, let my webview to load the page return false;      }//Otherwise, this link is not my Site page, so enable browser to process URLs Intent Intent = new Intent (Intent.action_view, Uri.parse (URL));  StartActivity (Intent);    return true; }} @Overridepublic boolean onKeyDown (int keycode, keyevent event) {//Check whether the event is returned if there is a page history if (keycode = = keyevent.ke        Ycode_back && Mwebview.cangoback ()) {mwebview.goback ();    return true; }//If it is not a return key or no web browsing history, keep the default//system behavior (may exit the activity) return Super.onkeydown (KeyCode, event);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.btn_nightmode:mwebview.loadurl ("Javasc        Ript:load_night () ");    Break        Case R.id.btn_lightmode:mwebview.loadurl ("Javascript:load_day ()");    Break    Default:break; }}

}

Ext.: http://blog.csdn.net/wwj_748/article/details/44835865

Android-webview for offline cache reading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.