(ii) Android Webview in depth (UP)

Source: Internet
Author: User
Tags delete cache

1 Android uses WebView implementation to invoke Android code in JS

in Java or Android, the interface occupies a large proportion, do programmers of course to understand the interface, haha! Android and JS seemingly horse and Beast, but because of the WebView connection in JS can call Android write code to achieve the function of Android! Android and JS are like Java and C + + by the JNI connection, the two are also connected by the interface. No more nonsense, here's a simple example of calling Android code in JS

Achieve Android Features!
1. First describe the differences between WebView, Webviewclient and webchromeclient:
In the design of WebView, not everything should be WebView class dry, some chores are assigned to other people, so WebView concentrate on doing their own analysis, rendering work on the line. Webviewclient is to help WebView handle various notifications, request events, etc., Webchromeclient is the Auxiliary WebView Processing Javascript dialog box, website icon, website title.
2. Feature implementation: Use Android WebView to load an HTML page, define a button in the HTML page, click the button to pop up a toast.
3. Implementation steps:
① defines an interface class that passes in the context object and defines the method to be implemented in JS in the interface class.
② defines an HTML file under the assets resource bundle, defining a Button.button Click event in the file as a JS function.
③ defines a WebView component in XML, gets WebView in the activity class, and sets the WebView parameter, paying particular attention to setting the WebView support JS and adding the defined JS interface class to the WebView, which can then be used in JS The function defined in the interface class. That is:
Mywebview.getsettings (). Setjavascriptenabled (True);
Mywebview.addjavascriptinterface (New Javascriptinterface (this), "Android");
④ uses WebView to load local HTML files by: Mywebview.loaddata (HTMLText, "text/html", "Utf-8"), where HTMLText reads the inside of the assets report in HTML as a string Specific code See source! Ha ha.
4. Implement use the return key to return to the previous page:
Set the WebView key to listen, listen for the expiration return key and determine if the webpage can return, use WebView's GoBack () to return to the previous page.
Nonsense not much to say, on the code:

XML layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "vertical" >    <webview        android:id= "@+id/mywebview" android:layout_width= "Fill_        Parent "        android:layout_height=" fill_parent "        android:clickable=" false "        Android:focusableintouchmode = "false"/></linearlayout>
Java code:
Package Com.sihuatech.webview;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Android.app.activity;import Android.os.bundle;import Android.view.keyevent;import Android.webkit.WebView;import Android.webkit.webviewclient;public class Mainactivity extends activity {/** Called when the activity is first created. */ Private WebView Mywebview; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.main); Mywebview = (WebView) Findviewbyid (R.id.mywebview); Mywebview.getsettings (). Setjavascriptenabled (True); Mywebview.addjavascriptinterface (New Javascriptinterface ( This), "Android"); String HTMLText = getfromassets ("test.html"); Mywebview.loaddata (HTMLText, "text/html", "utf-8"); Mywebview.setwebviewclient (New Mywebviewclient ());} This key listens for the return key and is able to return to the previous page (via web page hostlistery) public boolean onKeyDown (int keycode, keyevent event) {if (keycode = = Keyevent.keycode_back) && Mywebview.cangoback ()) {mywebview.goback (); RetuRN true;} Return Super.onkeydown (KeyCode, event);} public string Getfromassets (string fileName) {try {inputstreamreader inputreader = new InputStreamReader (Getresources () . Getassets (). open (FileName); BufferedReader bufreader = new BufferedReader (Inputreader); String line = ""; String result = ""; (line = Bufreader.readline ()) = null) Result + = Line;if (Bufreader! = null) bufreader.close (); if (Inputreader! = null) inputreader.close (); return Result;} catch (Exception e) {e.printstacktrace ();} return null;} Class Mywebviewclient extends Webviewclient {@Overridepublic Boolean shouldoverrideurlloading (WebView view, String URL) {//TODO auto-generated method Stubview.loadurl (URL); return true;}}}

Package Com.sihuatech.webview;import Android.content.context;import Android.widget.toast;public class Javascriptinterface {Private Context mcontext;/** instantiate the interface and set the Context */public Javascriptinterfa CE (Context c) {mcontext = C;} /** Show A toast from the Web page */public void Showtoast (String toast) {Toast.maketext (Mcontext, Toast, Toast.length_sho RT). Show ();}}
HTML code:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

2.Android WebView Cache

The WebView control is often used in projects, and when an HTML page is loaded, the database and cache two folders are generated in the/data/data/app package directory as shown in the following example:


The requested URL record is saved in Webviewcache.db, and the content of the URL is saved under the Webviewcache folder. to make it easier to understand, then simulate a case, define an HTML file, display an image in it, load it with WebView, and then try to read the image from the cache and display it.
First step: Create a new Android project named Webviewcache. The directory structure is as follows:

Step Two: Create a new HTML file under the assets directory named index.html

<span style= "FONT-SIZE:14PX;" ><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Step Three: Modify the Main.xml layout file, a Button for the WebView control (click Load Cached image), the code is as follows:
<span style= "FONT-SIZE:14PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" fill_parent "><webview android:layout_width=" fill_parent "android:layout_height=" wrap_content "android:id=" @+id/WebView "/><button android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_gravity=" "Center_horizontal" android:text= "read picture from cache" Android:id= "@+id/button"/></linearlayout></span>
Fourth Step: Modify the main core program Webviewcachedemo.java, here I only loaded the Index.html file, button events temporarily not written, the code is as follows:
<span style= "FONT-SIZE:14PX;" >public class Webviewactivity extends Activity {private WebView webview;private static final String url= "File:///andro Id_asset/index.html "; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); webview= (WebView) Findviewbyid (r.id. WebView); Webview.loadurl (URL);}} </span>
Fifth Step: Add access to the network in the Androidmainifest.xml file:

<uses-permission android:name= "Android.permission.INTERNET"/>
The results are as follows:


At this point we have one more record in the cache.table in webviewcache.db as shown:


In the cache/webviewcache/directory more than a 10D8D5CD file, just and cache.table in the filepath, we can conclude that this
The file is the picture we dragged down from the Internet:
To verify the conjecture, I add an event response to the Button, which is the popup Dialog, which loads the cached picture, the complete code is as follows:

<span style= "FONT-SIZE:14PX;" >public class Webviewactivity extends Activity {private WebView webview;private static final String url= "File:///andro Id_asset/index.html "; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); webview= (WebView) Findviewbyid (r.id. WebView); Webview.loadurl (URL);//Click the button to pop up the dialog box button button= (button) Findviewbyid (R.id.button); Button.setonclicklistener (new View.onclicklistener () {public void OnClick (View v) {ImageView imageview=new ImageView (webviewactivity.this); Imageview.setimagebitmap (Getpicturefromcache ()); Builder builder=new Android.app.AlertDialog.Builder (webviewactivity.this);//Settings dialog box icon builder.settitle ("View picture from cache"); Builder.setview (ImageView);//Exit button Builder.setpositivebutton ("Exit", new Onclicklistener () {public void OnClick ( Dialoginterface dialog, int which) {//Close Alert Dialog Frame Dialog.cancel ();}); Builder.create (). Show ();}); /*** get pictures from Cache * * @return */private Bitmap Getpicturefromcache () {Bitmap biTmap=null;try {//here to die, in the actual development project to be flexible to use the file File=new file (Getcachedir () + "/WEBVIEWCACHE/10D8D5CD"); FileInputStream instream=new fileinputstream (file); Bitmap=bitmapfactory.decodestream (InStream);} catch (Exception e) {e.printstacktrace ();} return bitmap;}} </span>
Sixth step: Run the project again, click on the button and the effect is as follows:

3.Android WebView Delete Cache

<span style= "FONT-SIZE:14PX;" > Delete cache saved on Phone:/clear the cache before time numdaysprivate int Clearcachefolder (File dir, long numdays) {int Deletedfil Es = 0;if (dir!= null && dir.isdirectory ()) {try {for (File child:dir.listFiles ()) {if (Child.isdirectory ()) {dele Tedfiles + = Clearcachefolder (child, numdays);} if (child.lastmodified () < numdays) {if (Child.delete ()) {deletedfiles++;}}}} catch (Exception e) {e.printstacktrace ();}} return deletedfiles;} Turn off Use cache//Priority cache: Webview.getsettings (). Setcachemode (websettings.load_cache_else_network);// Do not use cache: Webview.getsettings (). Setcachemode (Websettings.load_no_cache); When exiting the application, add the following code, file File = Cachemanager.getcachefilebasedir (); if (file = null && file.exists () && file.isdirectory ()) {for (file Item:file.listFiles ()) {Item.delete ();} File.delete ();} Context.deletedatabase ("webview.db"); Context.deletedatabase ("webviewcache.db"); </span><span style= " font-size:24px; " ></span>

(ii) Android Webview in depth (UP)

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.