Android Deep Understanding webview--on

Source: Internet
Author: User

Summary

As an Android developer, we all know that a high-performance WebKit kernel browser is built into the phone, encapsulated in the SDK as a component called WebView. Let's talk about how to use WebView in Android today.
This article original, reprint please specify address: http://blog.kymjs.com/

As an Android developer, we all know that a high-performance WebKit kernel browser is built into the phone, encapsulated in the SDK as a component called WebView.
In the development process should pay attention to several points:
1. This is the most basic androidmanifest.xml that must be added to access the network permissions.
2. If there is JavaScript on the page visited, the WebView must be set to support JavaScript.

Webview.getsettings (). Setjavascriptenabled (True);

3. If the page links, if you want to click on the link to continue in the current browser response, instead of the new Android system browser should link in the ring, you must overwrite the WebView Webviewclient object.

Mwebview.setwebviewclient (New Webviewclient () {public Boolean shouldoverrideurlloading (WebView view, String URL) { View.loadurl (URL); return true;});

4. If you do not do any processing, browse the Web page, click the System "back" button, the entire Browser will call finish () and end itself, if you want to browse the page fallback rather than launch the browser, you need to process and consume the back event in the current activity. (The code is somewhat streamlined)

public boolean onKeyDown (int keycode, keyevent event) {if (keycode = = keycode_back) && mwebview.cangoback ()) {MW Ebview.goback (); return true;} Return Super.onkeydown (KeyCode, event);}
and JS Intermodulation

Now that you can display the Web page, you can also let the Web page manipulate the local method. (because one line doesn't fit, indentation I adjust)

public class Webviewdemo extends Activity {private WebView mwebview;private Handler mhandler = new Handler (); public void OnCreate (Bundle icicle) {Setcontentview (r.layout.webviewdemo); Mwebview = (WebView) Findviewbyid (R.id.webview); WebSettings websettings = Mwebview.getsettings (); Websettings.setjavascriptenabled (TRUE); Mwebview.addjavascriptinterface (New Object () {public  void clickonandroid () {  mhandler.post (new Runnable () { Public  void Run () {   Mwebview.loadurl ("Javascript:wave ()");}});}  , "demo"); Mwebview.loadurl ("file:///android_asset/demo.html"); }}

Let's look at Addjavascriptinterface (object obj,string InterfaceName), a method that binds a Java object to a JavaScript object, and the JavaScript object name is InterfaceName (Demo), scope is global. This initializes the WebView so that the bound Java object can be accessed directly through Javascript:window.demo in the WebView loaded page. Let's see how it's called in HTML.

This makes it possible to invoke the Java object's Clickonandroid () method in JavaScript, and we can define many methods in this object (such as texting, calling a contact list, and so on), where the Wave () method is called in Java Examples of JavaScript.

It is important to note that the Java objects and methods to be bound in the Addjavascriptinterface method are running in another thread and cannot be run in the thread that constructs them, which is also the purpose of using Handler.

Deep use of WebView let JS call Android code
    1. First, the differences between WebView, Webviewclient and Webchromeclient are briefly described:
      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 WebView in Android to load an HTML page, define a button in the HTML page, and click the button to pop up a toast.

    3. Implementation steps:
      First, define an interface class, pass in the context object, define the method to be implemented in JS in the interface class.
      Next, define an HTML file under the Assets Resource bundle and define a Button.button Click event in the file as a JS function.
      A WebView component is then defined in the XML, gets WebView in the activity class, and sets the WebView parameter, where special attention is paid to setting the WebView support JS and adding the defined JS interface class to the WebView, after which the JS can benefit Use the function defined in the interface class. That is:

      Mywebview.getsettings (). Setjavascriptenabled (True);

      Mywebview.addjavascriptinterface (New Javascriptinterface (this), "Android");

The last way to load a local HTML file with WebView is to:

Mywebview.loaddata (HTMLText, "text/html", "utf-8");

The htmltext here is to read the contents of the assets in HTML as a string.
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.

WebView Cache

If the WebView control is used in the project, when the HTML page is loaded, the database and cache two folders will be generated in the/data/data/package (my phone is not rooted.)
The requested URL record is saved in Webviewcache.db, and the content of the URL is saved under the Webviewcache folder. You can try it yourself, define an HTML file, display a picture in it, load it with WebView, and then try to read the image from the cache and display it.

WebView Deleting a cache

In fact, you already know the location of the cache, then the deletion is very simple, get to this cache, and then delete him just fine.
Delete the cache saved on the phone

private int Clearcachefolder (File dir,long numdays) {   int deletedfiles = 0;  if (dir!= null && dir.isdirectory ()) {    try {for      (File child:dir.listFiles ()) {      if ( Child.isdirectory ()) {        Deletedfiles + = Clearcachefolder (child, numdays);        }        if (child.lastmodified () < numdays) {          if (Child.delete ()) {           deletedfiles++;           }      }    }} catch (Exception e) {      e.printstacktrace ();     }  }  return deletedfiles; }

The ability to enable caching is also controllable

Priority to use 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 to completely empty the cache

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");
WebView Handling 404 Errors

The page will also encounter a problem, that is, the Web page may not be found, webview of course, can also be handled (code if the whole is too much to paste, here is only the important part of it)

public class Webviewactivity extends Activity {private Handler Handler = new Handler () {public void handlemess                  The Age (Message msg) {if (msg.what==404) {//home page does not exist//loading the local assets folder under the error prompt page 404.html                    Web.loadurl ("file:///android_asset/404.html");                    }else{Web.loadurl (homepage);      }              }};              @Override protected void OnCreate (Bundle savedinstancestate) {web.setwebviewclient (new webviewclient () { public boolean shouldoverrideurl (WebView view,string URL) {if (Url.startswith ("/http") && Getrespst              ATUs (URL) ==404) {view.stoploading ();        Load the local Assets folder under the error prompt page 404.html view.loadurl ("file:///android_asset/404.html");        }else{view.loadurl (URL);    } return true;      }      }); New Thread (New Runnable () {public void run () {Message msg = new MEssage (); Here to determine whether the home page exists, because the home page is loaded through Loadurl,//At this time will not perform shouldoverrideurlloading to make a page whether the existence of the judgment//Enter the homepage, the link to the home page, link to other pages              The Shouldoverrideurlloading method must be executed if (Getrespstatus (homepage) ==404) {msg.what = 404;          } handler.sendmessage (msg);      }). Start (); }}
Not finished

Because WebView is too much to use, there are two parts, the next part to tell you about WebView scrolling state monitoring and how to get session and write cookies ~ ~

Android Deep Understanding webview--on

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.