Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/44619181
Some time to do the project, in the project with the WebView components, encountered some problems, so specifically to find some information, learning how to solve, now will learn the content into a blog record here, convenient to meet again later can quickly see and solve the problem. We know that Android WebView is a large component, in fact WebView is a framework integrated with the famous browser engine WebKit, which is mainly used to load rendered Web pages in Android apps. Well, before this study note, I also studied Google's official documents, introduced the basic usage of webview, and translated it, the address is: http://blog.csdn.net/allen315410/article/details/ 44647171, please do not use WebView classmate, first look at this article, then look at my following content.
Get the title information for a Web page
When we open some applications, such as today's headline news client, some pages are loaded with WebView, but often at the top of the interface there will be a title bar, and the content of the title bar is not our own in the program to write dead, but the dynamic from the page to get, then how do we get it? As we all know, in the HTML, a complete page will inevitably contain <title></title> tags, the label is the content of the title, so we just need to get the title tag in the HTML content to be able to. To get the title content, you must set the WebView setwebchromeclient (webchromeclient Client) method, passing a webchromeclient Object and overrides the Shouldoverrideurlloading (WebView view, String URL) method, which callback the title is the content between <title></title> tags. For example:
... mwebview = (WebView) Findviewbyid (R.id.webview);//Turn on JavaScript support Mwebview.getsettings (). setjavascriptenabled ( true);//Load Page mwebview.loadurl ("http://www.baidu.com");//force the page to open in WebView, Prevents the use of the system's default browser to open the Web page mwebview.setwebviewclient (new Webviewclient () {@Overridepublic Boolean shouldoverrideurlloading ( WebView view, String URL) {view.loadurl (URL); return super.shouldoverrideurlloading (view, URL);}}); Mwebview.setwebchromeclient (New Webchromeclient () {@Overridepublic void Onreceivedtitle (WebView view, String title) {/ /onreceivedtitle can callback the page's Titletv_title.settext (title); Super.onreceivedtitle (view, title);}); ...
As shown, the Web page is open in WebView and the title is now on the TextView header.
Download files with WebView
Similarly, when we use the browser, many times will need to download files, browser is a very powerful application, can help us to download files on the Internet, if we have integrated WebView components in our application, where the rendered page also has files available for download, how do we do the download function? Also, since the browser is so powerful, our webview components are not bad. Let's see how WebView downloads the file.
public class Downloadactivity extends Activity {private WebView mwebview; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.activity_download); Mwebview = (WebView) Findviewbyid (R.id.webview);// Turn on JavaScript support Mwebview.getsettings (). Setjavascriptenabled (True); Mwebview.loadurl ("Http://img.mukewang.com/down /54eec5f10001b17600000000.zip "); Mwebview.setwebviewclient (new Webviewclient () {@Overridepublic Boolean Shouldoverrideurlloading (WebView view, String URL) {view.loadurl (URL); return super.shouldoverrideurlloading (View, (URL);}}); /Listen download Mwebview.setdownloadlistener (new Downloadlistener () {@Overridepublic void Ondownloadstart (string url, string UserAgent, String contentdisposition, String mimetype, long contentlength) {System.out.println ("url:" + URL); if ( Url.endswith (". zip")) {//If the incoming URL contains a. zip file, open the download thread System.out.println ("Download start ..."); New Downloadthread (URL ). Start ();}}});} /** * Executing the downloaded thread */class downloadthread extends thread {private string murl;public downloadthread (String url) {this.murl = ur l;} @Overridepublic void Run () {try {URL httpurl = new URL (murl); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); Conn.setdoinput (true); Conn.setdooutput (True) ; Conn.setconnecttimeout (conn.setreadtimeout); InputStream in = Conn.getinputstream (); FileOutputStream out = null;//Gets the download path file downloadFile; File sdfile;if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {downloadFile = Environment.getexternalstoragedirectory (); sdfile = new File (downloadFile, "Download.zip"); out = new FileOutputStream ( Sdfile);} Byte[] B = new byte[8 * 1024];int len;while (len = In.read (b))! =-1) {if (out! = null) {Out.write (b, 0, Len);}} if (out! = null) {Out.close ();} if (in = null) {In.close ();} System.out.println ("Download success ..."); catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}}
In fact, especially simple, WebView has provided us with good one implementation of the download interface and callback method, this interface is Android.webkit.DownloadListener, we first call WebView Setdownloadlistener (Downloadlistener Listener) method, in the method parameters passed Downloadlistener object, override the Ondownloadstart method, in this method to open the download function of the thread, let the thread help us go to the server to download the file.
Processing of WebView error codes
What does webview mean by error code processing? When we use the Android device, there may be times when the network is bad or no network, the device will not be able to access the server, the HTML page cannot be loaded. In general, when our device loads an HTML without a network, it will pop up the Android default error page itself, such as:
OK, this is the Android system to give us the default page, is it worth us to spit a notch it? The same page presented to the user will also be scolded, then how should we deal with such a situation? The way is also very simple, there are 2 ways to achieve, one is to load a local HTML page, tell the network exception, and the second is to customize an error interface by layout, loading to the main interface. Well, neither of these implementations is the point, and we don't discuss how to make a nice HTML error page or a nice XML layout.
Monitoring WebView loading error is done in the Onreceivederror () method under Setwebviewclient () 's Delivery Webviewclient object, here is a simple way to handle it:
Mwebview.setwebviewclient (New Webviewclient () {... @Overridepublic void Onreceivederror (WebView view, int errorCode, String description, String failingurl) {//network exception, WebView load our custom page super.onreceivederror (view, ErrorCode, description, Failingurl); View.loadurl ("file:///android_asset/error.html");});
Well, the above code does a simple processing: Reload the local HTML static page of the assets directory.
What is WebView sync Cookiecookie? This requires some knowledge of the Java server, in short, the cookie is a caching mechanism on the server, for example, when we log in the first time we entered the login username and password, and saved the password, Then the next time we open this page again, we will automatically read the cookie to complete the automatic login. If the page containing the cookie is loaded with WebView, how can the same function be implemented? We only have to set WebView to sync with cookies.
public class Cookietestactivity extends Activity {private WebView mwebview;private Handler mhandler = new Handler () {Publi c void Handlemessage (Message msg) {//Sync cookiecookiesyncmanager.createinstance (cookietestactivity.this); Cookiemanager Cookiemanager = Cookiemanager.getinstance (); Cookiemanager.setacceptcookie (true); Cookiemanager.setcookie ("Http://192.168.1.105:8080/webs", msg.obj.toString ()); Cookiesyncmanager.getinstance (). sync (); Mwebview.loadurl ("http://192.168.1.105:8080/webs/index.jsp");};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.activity_download); MWebView = (WebView) Findviewbyid (R.id.webview);//Turn on JavaScript support Mwebview.getsettings (). Setjavascriptenabled (True); String url = "http://192.168.1.105:8080/webs/login.jsp"; new HttpCookie (Mhandler, URL). Start (); /** * Access server, read cookie information */class HttpCookie extends Thread {private Handler handler;private String Url;puBlic HttpCookie (Handler Handler, String url) {this.handler = Handler;this.url = URL;} @Overridepublic void Run () {//Use HttpClient to send a POST request to the server httpclient client = new Defaulthttpclient (); HttpPost post = new HttpPost (URL); list<namevaluepair> list = new arraylist<namevaluepair> (); List.add (New Basicnamevaluepair ("name", " Zhangsan ") List.add (New Basicnamevaluepair (" Age ",") "), try {post.setentity (new urlencodedformentity (list)); HttpResponse response = Client.execute (POST), if (Response.getstatusline (). Getstatuscode () = = 200) {//Access server succeeded, Read cookie information from the server abstracthttpclient absclient = (abstracthttpclient) client; list<cookie> cookies = Absclient.getcookiestore (). GetCookies (); for (Cookie cookie:cookies) {// Sends a cookie to the UI thread Log.d ("TAG", "name=" + cookie.getname () + ", age=" + cookie.getvalue ()); Message message = Message.obtain (); message.obj = cookie;handler.sendmessage (message); return;}} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (Clientprotocolexception e){E.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}}
Well, with the example code above, we'll soon know how to set the cookie to sync, and the main code is in handler.
WebView and JS Call confusion problem
This problem is often encountered, when we write in Java to invoke the JS code, the test is completely normal, but we publish the program, we need to confuse packaging, Confusion after the packaging of the survival of our. apk file, the APK installed on the device, the call JS again, you will find the method is invalid, this is a annoying time. In order to solve this problem, we need to do some protection of the JS call code, protection is very simple, just need to confuse the file in the Java layer of the call to ignore the code can be.
This is activity:
public class Mainactivity extends Activity {private WebView mwebview; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); MWebView = ( WebView) Findviewbyid (R.id.webview); Mwebview.loadurl ("file:///android_asset/index.html"); Mwebview.setwebviewclient (New Webviewclient () {@Overridepublic Boolean shouldoverrideurlloading (WebView view, String URL) {view.loadurl ("file:///android_asset/index.html"); return true;}); Mwebview.getsettings (). Setjavascriptenabled (True); Mwebview.addjavascriptinterface (new webhost (this), "JS");}}
Then we also write a call to the JS class:
public class Webhost {private Context Mcontext;public webhost (context context) {This.mcontext = context;} public void Calljs () {Toast.maketext (Mcontext, "Call from JS", Toast.length_short). Show ();}}
The JS code is as follows:
At this time the code written in the test phase is not a problem, and then when the confusion of packaging, there will be the possibility of invoking JS failure, workaround: In the confusion configuration file proguard.cfg Ignore webhost inside the method-keep public class Com.example.webview_02.webhost{public <methods>}
Android Development using WebView combat skills