Android WebView use in layman's terms

Source: Internet
Author: User

Many Android apps now have a built-in interface that can display Web pages, and this interface is typically rendered by a component called WebView, and learning that component can improve the extensibility of your app development.

First of all, webview some of the advantages:

    • You can display and render the Web page directly, display the page directly
    • WebView can be directly used in HTML files (on the network or in local assets) for layout
    • Interacting with JavaScript calls

First, basic use

First, the layout is a basic simple control:

<webview        android:id= "@+id/webview1"        android:layout_width= "fill_parent"        android:layout_height= " Fill_parent "        android:layout_margintop=" 10DP "/>

At the same time, because the room to access the network, so manifest must add Uses-permission:

<uses-permission android:name= "Android.permission.INTERNET"/>

You can get a reference to webview in the activity and load a URL:

WebView = (webview) Findviewbyid (r.id.webview1); Webview.loadurl ("http://www.baidu.com/");//webview.reload ();// Reload page

This time found a problem, after launching the application, automatically opened the system built-in browser, to solve this problem need to set webviewclient for WebView, and override the method:

Webview.setwebviewclient (New Webviewclient () {            @Override public            boolean shouldoverrideurlloading (WebView View, String URL) {                view.loadurl (URL);                return true;            }        });

If you define a page loading progress ProgressBar, need to show to the user, you can get the WebView page loading progress as follows:

Webview.setwebchromeclient (New Webchromeclient () {            @Override public            void onprogresschanged (webview view, int newprogress) {                //get the newprogress and Refresh progress bar            }        });

Each page, there is a title, such as www.baidu.com the title of this page is "Baidu a bit, you know", then how to know the current webview is loading the title of the page:

Webview.setwebchromeclient (New Webchromeclient () {            @Override public            void Onreceivedtitle (WebView view, String title) {                Titleview.settext (title);//a TextView            }        });

Ii. downloading files through the WebView control

Usually WebView rendering interface contains a link to download the file, click on the link, you should start to perform the download and save the file to the local. There are usually two ways to download a file in a page WebView:

1. You can download and save files by writing Java IO code on a thread (good controllability)

2. Call the system download module (code simple)

Method One:

First, write a thread class to download and save the file

public class Httpthread extends Thread {private String murl;  Public Httpthread (String murl) {this.murl = Murl;    } @Override public void Run () {URL url;      try {url = new URL (murl);      HttpURLConnection conn = (httpurlconnection) url.openconnection ();      Conn.setdoinput (TRUE);      Conn.setdooutput (TRUE);      InputStream in = Conn.getinputstream ();      File DownloadFile;      File Sdfile;      FileOutputStream out = null; if (Environment.getexternalstoragestate (). Equals (environment.media_unmounted)) {downloadFile =        Environment.getexternalstoragedirectory ();        Sdfile = new File (downloadFile, "test.file");      out = new FileOutputStream (sdfile);      }//buffer 4k byte[] buffer = new byte[1024 * 4];      int len = 0;      while (len = in.read (buffer))! =-1) {if (out! = NULL) out.write (buffer, 0, Len);      }//close Resource if (out! = null) out.close ();      if (in = null) {in.close ();    }} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }  }}

Then to implement a Downloadlistener interface, this interface implementation method Ondownloadstart (), when the user clicks on a downloadable link, the callback method is called at the same time to pass in the URL of the link, You can then plug the URL into the httpthread to download the operation:

Create Downloadlistener (WebKit package) class Mydownloadlistenter implements downloadlistener{  @Override public  Void Ondownloadstart (string URL, String useragent,    string contentdisposition, String mimetype, long contentlength) {      System.out.println ("url = = >" + URL);      New Httpthread (URL). Start ();  }    } Add Monitoring Webview.setdownloadlistener (new Mydownloadlistenter ()) to WebView;

Method Two:

Send a Action_view intent directly:

Class Mydownloadlistenter implements downloadlistener{        @Override public        void Ondownloadstart (String URL, String useragent,      string contentdisposition, String mimetype, long contentlength) {  System.out.println ("url = = = = > "+ url");  New Httpthread (URL). Start ();    Uri uri = uri.parse (URL);  Intent Intent = new Intent (Intent.action_view, URI);  StartActivity (intent);        }    }

Third, error handling

When we use the browser, usually due to the loading of the page server for various reasons for various errors, the most common such as 404 error, usually the browser will prompt an error prompt page. In fact, the error page is that the browser is loading a local page that prompts the user to make a mistake at the moment.

However, when we use the WebView control in our app to encounter errors such as 404, it is ugly to display the error page in the browser, then our app will need to load a local error prompt page. That is, webview how to load a local page.

1. First we need some HTML file, such as error_handle.html, this file is when the error should be displayed to the user to see the error page, try to do a bit more beautifully. Then place the file under the Assets folder in the root directory of your code.

2. We then need to replicate the Webviewclient Onrecievederror method, which returns the error code, which can be handled differently depending on the type of error.

Webview.setwebviewclient (New Webviewclient () {             @Override public      void Onreceivederror (webview view, int ErrorCode,        string description, String failingurl) {    switch (errorCode)    {case    httpstatus.sc_not_ FOUND:        view.loadurl ("file:///android_assets/error_handle.html");        Break;}}  );

In fact, when the error, we can choose to hide the WebView, and display native error handling control, this time only need to show the onreceivederror inside the error handling native control and hide the webview at the same time.

Iv. webview Sync Cookies

Cookies are the usual information that the server uses to keep each customer, and the next time a customer enters a page such as a login, the server detects cookie information and, if passed, directly into the landing page.

In WebView, if you have already logged in, then the next time you enter the same landing interface, if you need to log in again, it will be very annoying, so here is a way to webview sync cookies.

1. First, we assume that the landing interface of a website needs to provide two parameters, one is name, and one is PWD, then if you log on to this page, you must give the two information. We assume that the server has registered a name of jason,pwd of 123456 for this account.

2. Below, write a thread used to automatically login the name and PWD, get cookie information in the response returned by the server, and save the cookie later, here is the code for this thread:

public class HttpCookie extends Thread {private Handler mhandler;  Public HttpCookie (Handler mhandler) {this.mhandler = Mhandler;    } @Override public void Run () {HttpClient client = new Defaulthttpclient (); HttpPost post = new HttpPost ("");//this place should add the login address list<namevaluepair> List = new ARR    Aylist<namevaluepair> ();    List.add (New Basicnamevaluepair ("name", "Jason"));    List.add (New Basicnamevaluepair ("pwd", "123456"));      try {post.setentity (new urlencodedformentity (list));      HttpResponse reponse = Client.execute (POST); if (Reponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {abstracthttpclient absclient = (AbstractHttpClient        ) client;        list<cookie> cookies = Absclient.getcookiestore (). GetCookies ();          for (cookie cookie:cookies) {if (cookie = null) {//todo//this place would get the cookie }}}} catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();    } catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstacktrace ();    } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }  }}

Because this is a child thread, it needs to be created and executed in the main thread.

At the same time, because in fact the child thread, then inside must contain a handler element, used to notify the main thread to synchronize and save when the cookie is successfully obtained. When initializing this sub-thread, it is necessary to pass the handler on the main thread, then send a message in the Todo of the above code, let the main thread record the cookie, and the message sent will be included in the cookie information:

if (cookie = null) {  //todo  //this Place would get the cookie  message msg = new Message ();  Msg.obj = cookie;  if (Mhandler! = null) {    mhandler.sendmessage (msg);    return;}  }

Then in the main line approached (WebView loading login), in handler will obtain the cookie information, the following will be stored and synchronized to the cookie:

Private Handler Mhandler = new Handler () {public    void Handlemessage (android.os.Message msg)     {      Cookiesyncmanager.createinstance (mainactivity.this);      Cookiemanager cookiemgr = Cookiemanager.getinstance ();      Cookiemgr.setacceptcookie (true);      Cookiemgr.setcookie ("", msg.obj.toString ());//This place should add the login host address (not the login index address) 
   cookiesyncmanager.getinstance (). sync ();      Webview.loadurl ("");//Login index address    };  };

This time found that WebView loaded login index page can be automatically logged in and display the login interface.

V. WebView interaction with JavaScript

1. WebView Call JS

Mwebview.loadurl ("Javascript:do ()");

The above is webview in the call JS in a called do method, the JS is located in the HTML file is roughly the following:

2. JS Call WebView

We assume that the following local classes are to be called for JS:

Package Com.test.webview;class Demojavascriptinterface {  demojavascriptinterface () {  }  /**   * This isn't called on the UI thread. Post a runnable to invoke   * Loadurl on the UI thread.   */Public  void Clickonandroid () {      mhandler.post (new Runnable () {public    void run () {        //todo    }      });  }    }

First, set the WebView to:

Mwebview.setjavascriptenabled (TRUE);

The local class (called by JS) is then mapped out:

Mwebview.addjavascriptinterface (New Demojavascriptinterface (), "demo");

"Demo" This name is published to the JS call, then JS Long can directly call the following code in the local Demojavascriptinterface class method:

<body>      ...</body>

Vi. WebView and JavaScript call confusion problems

If JS in the WebView calls the local method, normally the release of the debug package JS call is not a problem, but usually release the commercial version of the APK is to be confused steps, this time will find that the normal JS is called before the normal call local method.

This is because the confusion of the local code has been a reference to the upset, resulting in JS code can not find the address of the local method.

To solve this problem, it is simple to add some code in the Proguard.cfg file, declaring that the code in the local JS call is not confused. The following examples illustrate:

In the fifth section, the class demojavascriptinterface called by JS is named Com.test.webview, so it is necessary to include in the Proguard.cfg file:

-keep public class com.test.webview.demojavascriptinterface{public    <methods>;}

If the inner class, it is roughly written as follows:

-keep public class com.test.webview.demojavascriptinterface$innerclass{public    <methods>;}

If the Android version is newer, you may need to add the following code:

-keepattributes *annotation*  -keepattributes *javascriptinterface*

From: http://www.cnblogs.com/soaringEveryday/p/4495221.html

Android WebView use in layman's terms

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.