Android's WebView app

Source: Internet
Author: User
Tags setcookie

This example mainly introduces how to design the UI through WebView (how to return a friendly interface to the user when the Web UI requests the error), how to use WebView to implement the download function, and to implement the free login function via cookies.


XML layout file

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" > <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_co            Ntent "android:orientation=" horizontal "> <imagebutton android:id=" @+id/id_back " Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:background= "@drawa            Ble/selector_back "/> <textview android:id=" @+id/id_url "android:singleline=" true "            android:gravity= "center" android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:text= "url" android:textcolor= "#44000000" Android  : textsize= "23sp"/> <imagebutton          Android:id= "@+id/id_refresh" android:layout_width= "wrap_content" android:layout_height= "WR         Ap_content "android:background=" @drawable/selector_refresh "/> </LinearLayout> <view Android:layout_width= "Match_parent" android:layout_height= "1DP" android:background= "#22000000"/> & Lt WebView android:id= "@+id/id_webview" android:layout_width= "match_parent" android:layout_height= "MATC H_parent "/></linearlayout>

Body Function Code

public class Mainactivity extends Activity implements Onclicklistener{private WebView mwebview;private ImageButton MBACKBTN, mrefreshbtn;private TextView murltv;private Handler mhandler = new Handler () {public void Handlemessage (Android . os. Message msg) {String cookie = (string) msg.obj; System.out.println (cookie); Cookiesyncmanager.createinstance (Mainactivity.this); Cookiemanager Cookiemanager = Cookiemanager.getinstance (); Cookiemanager.setacceptcookie (true); Cookiemanager.setcookie ("http://10.10.1.24/android%20web/vebview.php", cookie); Cookiesyncmanager.getinstance (). sync (); Mwebview.loadurl ("http://10.10.1.24/android%20web/vebview.php");};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Mwebview = (WebView) Findviewbyid (r.id.id_webview); mbackbtn = (ImageButton) Findviewbyid ( R.id.id_back); mrefreshbtn = (ImageButton) Findviewbyid (r.id.id_refresh); MURLTV = (TextView) Findviewbyid (r.id.id_url ); Mbackbtn.setonClicklistener (This), Mrefreshbtn.setonclicklistener (This), Mwebview.loadurl ("Http://what"); Mwebview.setwebchromeclient (New Webchromeclient () {/** * Gets the HTML page title */@Overridepublic void Onreceivedtitle (WebView View, String title) {Murltv.settext (title); Super.onreceivedtitle (view, title);}}); Mwebview.setwebviewclient (New Webviewclient () {@Overridepublic Boolean shouldoverrideurlloading (WebView view, String URL) {view.loadurl (URL); return super.shouldoverrideurlloading (view, URL);} /** * Request Page error handling */@Overridepublic void Onreceivederror (WebView view, int errorcode,string description, String failingurl) { Super.onreceivederror (view, ErrorCode, description, Failingurl); Mwebview.loadurl ("file:///android_asset/error.html");}); * * Click on the download link processing * is direct download or through the browser download */mwebview.setdownloadlistener (new Mydownloadlistener ());/** * with webview cookies for free login function */new HttpCookie (Mhandler). Start ();} Class Mydownloadlistener implements downloadlistener{@Overridepublic void Ondownloadstart (string url, string useragent , StringContentdisposition, String mimetype, long contentlength) {/** * Click the download link and download the file as apk * To start the download file */if (Url.endswith (". apk")) { New Httpthread (URL). Start (); Uri uri = uri.parse (URL), Intent Intent = new Intent (Intent.action_view, URI); startactivity (Intent);}} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.id_refresh:mwebview.reload (); Break;case r.id.id_ Back:finish (); break;}}}

threads that implement the download feature

public class Httpthread extends Thread {private string murl;public httpthread (String url) {this.murl = URL;} @Overridepublic void Run () {InputStream is = null; FileOutputStream fos = null;try {URL httpurl = new URL (murl); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); Conn.setdoinput (true); Conn.setdooutput (True) ; Conn.setconnecttimeout (5000); File Downloadfolder; File Downloadfile;is = Conn.getinputstream (); if (Environment.getexternalstoragestate (). Equals (Environment.media_ Mounted) {Downloadfolder = new File (Environment.getexternalstoragedirectory (). GetAbsolutePath () + File.separator + " Webdownd "), if (!downloadfolder.exists ()) {Downloadfolder.mkdir ();} DownloadFile = new File (Downloadfolder, "test.apk"); fos = new FileOutputStream (downloadfile);} byte[] buffer = new Byte[1024];int len;while (len = is.read (buffer))! =-1) {fos.write (Buffer,0,len);} System.out.println ("Download sucess");} catch (Exception e) {e.printstacktrace ();} Finally{try {if (is = null) is.close (); if (FOS! = null) Fos.close ();} catch (IOException e) {e.printstacktrace ();};}}}

Cookie Fetch Thread

public class HttpCookie extends Thread {private Handler mhandler;public HttpCookie (Handler Handler) {This.mhandler = Handl ER;} @Overridepublic void Run () {HttpClient client = new Defaulthttpclient (); HttpPost post = new HttpPost ("http://10.10.1.24/android%20web/login.php"); list<namevaluepair> list = new arraylist<namevaluepair> (); List.add (New Basicnamevaluepair ("name", " Zhangliang ")); List.add (New Basicnamevaluepair (" pwd "," 123 ")); try {post.setentity (new urlencodedformentity (list)); HttpResponse response = Client.execute (POST), if (Response.getstatusline (). Getstatuscode () = = +) {abstracthttpclient Absclient = (abstracthttpclient) client; list<cookie> cookies = Absclient.getcookiestore (). GetCookies (); String ck = null;for (Cookie cookie:cookies) {System.out.println (Cookie.getname () + cookie.getvalue ()); CK = Cookie.getna Me () + "=" + cookie.getvalue () + ";d omain=" + cookie.getdomain () + ";";} Message message = new Message (); message.obj = ck;mhandler.sendmessage (message);}} CatCH (Exception e) {e.printstacktrace ();}}} 


The following sections are the PHP backend code

Landing page

<?php$name = $_cookie[' name ']; $age = $_cookie[' pwd '];if (!empty ($name)) {header ("Location:welocom.html");}? ><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

Cookie Settings page

<?php$name = $_post[' name ']; $age = $_post[' pwd '];setcookie ("name", $name, Time () + 3600); Setcookie ("pwd", $age, Time ( ) + 3600), if (!empty ($name)) {echo "welcom to login!";}? >

SOURCE download


Android's WebView app

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.