Android recording 25-WebView for offline cache reading, android25-webview
Android recording 25-WebView for offline caching
This blog is designed to provide offline download and offline reading functions, which are common in many reading apps. A typical application is Netease news. What is offline download? In fact, this concept is vague, whether it is downloaded offline or offline after the download, but people who have a little bit of brains know how to download it after there is no network? So the offline download function is"Download resources to the local device when there is a network", Offline reading is"Read locally cached Article resources when there is no network or the network is poor". In this way, we can clearly understand the specific functional requirements.
Implementation
Here, Xiao Wu provides two implementation ideas: one is to write logic by yourself, and the other is to implement it through the cache function provided by WebView itself.
First, let's talk about the first idea:
The second idea is to use the cache function provided by WebView to achieve offline reading.
Here, Wu followed the example of the previous blog to add code.
Reference 1: http://www.open-open.com/lib/view/open1392188052301.html
Reference 2: http://87426628.blog.163.com/blog/static/6069361820139183417725/
Android WebView cache can be divided into page cache and data cache
Page caching refers to loading html, JS, CSS, and other page or resource data for a webpage.
There are two types of data cache: AppCache and DOM Storage (Web Storage ).
AppCache is also our H5 cache. We can set the cache directory.
Dom Storage has two types: Session Storage and Local Storage. The former is Session-level Storage, and the page disappears after it is closed. The latter is Local Storage.
If our mobile phone has the root permission, we can see the file directory under/data/package_name/. We will find that webview is created for us.
App_webview, which should be the location of the cache directory of webview.
Public void initWebView () {mWebView. getSettings (). setJavaScriptEnabled (true); mWebView. getSettings (). setRenderPriority (RenderPriority. HIGH); // The cache policy is recommended to determine whether a network exists. If yes, use LOAD_DEFAULT. If no network exists, use LOAD_CACHE_ELSE_NETWORK mWebView. getSettings (). setCacheMode (WebSettings. LOAD_CACHE_ELSE_NETWORK); // sets the cache mode. // enables the DOM storage API function mWebView. getSettings (). setDomStorageEnabled (true); // enable the database storage API function mWebView. getSettings (). setDatabaseEnabled (true); String cacheDirPath = getFilesDir (). getAbsolutePath () + APP_CACHE_DIRNAME; Log. I ("cachePath", cacheDirPath); // sets the database cache path to mWebView. getSettings (). setDatabasePath (cacheDirPath); // API 19 deprecated // set the Application caches cache directory mWebView. getSettings (). setAppCachePath (cacheDirPath); // enable the Application Cache function mWebView. getSettings (). setAppCacheEnabled (true); Log. I ("databasepath", mWebView. getSettings (). getDatabasePath ());}
Here is an article in my blog:
Public void findView () {initWebView (); mWebView. setWebViewClient (new WebViewClient () {@ Override public void onLoadResource (WebView view, String url) {Log. I (TAG, "onLoadResource url =" + url); super. onLoadResource (view, url) ;}@ Override public boolean shouldOverrideUrlLoading (WebView view, String url) {Log. I (TAG, "intercept url =" + url); view. loadUrl (url); return true;} // call @ Override public void onPageStarted (WebView view, String url, Bitmap favicon) {Log. e (TAG, "onPageStarted"); super. onPageStarted (view, url, favicon);} // call @ Override public void onPageFinished (WebView view, String url) {super. onPageFinished (view, url) ;}@ Override public void onReceivedError (WebView view, int errorCode, String description, String 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 result) {Log. e (TAG, "onJsConfirm" + message); return super. onJsConfirm (view, url, message, result) ;}@ Override public boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result) {Log. e (TAG, "onJsPrompt" + url); return super. onJsPrompt (view, url, message, defaultValue, result) ;}}); mWebView. loadUrl (url );}
Complete 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 (); private static final String APP_CACHE_DIRNAME = "/webcache"; // private String url of the web cache directory; // webpage 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 settings available for javaScript. setJavaScriptEnabled (true); // bind the javaScript interface to call our Android code in javaScript // webView. addJavascriptInterface (new WebAppInterface (this), "Android"); // webView. setWebViewClient (new MyWebViewClient (); // load the html page under the 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 url) {Log. I (TAG, "onLoadResource url =" + url); super. onLoadResource (view, url) ;}@ Override public boolean shouldOverrideUrlLoading (WebView view, String url) {Log. I (TAG, "intercept url =" + url); view. loadUrl (url); return true;} // call @ Override public void onPageStarted (WebView view, String url, Bitmap favicon) {Log. e (TAG, "onPageStarted"); super. onPageStarted (view, url, favicon);} // call @ Override public void onPageFinished (WebView view, String url) {super. onPageFinished (view, url) ;}@ Override public void onReceivedError (WebView view, int errorCode, String description, String 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 result) {Log. e (TAG, "onJsConfirm" + message); return super. onJsConfirm (view, url, message, result) ;}@ Override public boolean onJsPrompt (WebView view, String url, String message, String defaultValue, 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 cache policy is recommended to determine whether a network exists. If yes, use LOAD_DEFAULT. If no network exists, use LOAD_CACHE_ELSE_NETWORK mWebView. getSettings (). setCacheMode (WebSettings. LOAD_CACHE_ELSE_NETWORK); // sets the cache mode. // enables the DOM storage API function mWebView. getSettings (). setDomStorageEnabled (true); // enable the database storage API function mWebView. getSettings (). setDatabaseEnabled (true); String cacheDirPath = getFilesDir (). getAbsolutePath () + APP_CACHE_DIRNAME; Log. I ("cachePath", cacheDirPath); // sets the database cache path to mWebView. getSettings (). setDatabasePath (cacheDirPath); // API 19 deprecated // set the Application caches cache directory mWebView. getSettings (). setAppCachePath (cacheDirPath); // enable the Application Cache function mWebView. getSettings (). setAppCacheEnabled (true); Log. I ("databasepath", mWebView. getSettings (). getDatabasePath ();} public void clearWebViewCache () {// clear the WebView cache database try {deleteDatabase ("webview. db "); deleteDatabase (" webviewCache. db ");} catch (Exception e) {e. printStackTrace ();} // WebView cached 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 the 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 () ;}}/*** used to control the page navigation ** @ author wwj_748 **/private class MyWebViewClient extends WebViewClient {/*** when used to click the link, the system calls this method */@ Override public boolean shouldOverrideUrlLoading (WebView view, String url) {if (Uri. parse (url ). getHost (). equals ("www.baidu.com") {// This Is My webpage, so do not overwrite it. Let my WebView load the page return false;} // otherwise, this link is not my website page, so enable the 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 Web page history if (keyCode = KeyEvent. KEYCODE_BACK & mWebView. canGoBack () {mWebView. goBack (); return true;} // if it is not a return key or there is no web browsing history, keep the default // system behavior (this activity may be exited) return super. onKeyDown (keyCode, event) ;}@ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. btn_nightmode: mWebView. loadUrl ("javascript: load_night ()"); break; case R. id. btn_lightmode: mWebView. loadUrl ("javascript: load_day ()"); break; default: break ;}}
}
Reprinted Please note: IT_xiao xiaowu
Blog: http://blog.csdn.net/wwj_748
Mobile development enthusiasts: 299402133