Android WebView Application

Source: Internet
Author: User

Android WebView Application

This example mainly introduces how to design the UI through the web page through WebView (how to return a friendly interface to the user when the web page UI request is incorrect), how to use WebView to implement the download function, and use cookies to implement the login-free function.

 

Xml layout File

 

 
  
   
  
 

Main 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 () {/*** get 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 the download link to process whether to download the file directly or through a browser */mWebView. setDownloadListener (new MyDownLoadListener ();/*** use the WebView cookie to implement the login-free function */new HttpCookie (mHandler ). start ();} class MyDownLoadListener implements DownloadListener {@ Overridepublic void onDownloadStart (String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {/*** click the download link and the downloaded file is apk *. */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 ;}}}

Thread for downloading

 

 

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 obtaining thread

 

 

public class HttpCookie extends Thread {private Handler mHandler;public HttpCookie(Handler handler) {this.mHandler = handler;}@Overridepublic void run() {HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(http://10.10.1.24/android%20web/login.php);List
 
   list = new ArrayList
  
   ();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() == 200){AbstractHttpClient absClient = (AbstractHttpClient) client;List
   
     cookies = absClient.getCookieStore().getCookies();String ck = null;for (Cookie cookie : cookies) {System.out.println(cookie.getName() + cookie.getValue());ck = cookie.getName() + = + cookie.getValue() + ;domain= + cookie.getDomain() + ;;}Message message = new Message();message.obj = ck;mHandler.sendMessage(message);}} catch (Exception e) {e.printStackTrace();}}}
   
  
 

 

The following is the php background code:

 

Login Page

 

 

Cookie settings page

 

 

 

 

 

 

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.