Non-blocking web-Request

Source: Internet
Author: User

This code fetches content from the web without blocking the UI (runs in the background in a thread). Once finished, it posts a handler that is picked up by the UI as soon as possible.

 

  1. Import java. Io. bufferedinputstream;
  2. Import java. Io. inputstream;
  3. Import java.net. url;
  4. Import java.net. urlconnection;
  5. Import org. Apache. http. util. bytearraybuffer;
  6. Public class iconic extends activity {
  7. Private string html = "";
  8. Private handler mhandler;
  9. Public void oncreate (bundle savedinstancestate ){
  10. Super. oncreate (savedinstancestate );
  11. Setcontentview (R. layout. Main );
  12. Mhandler = new handler ();
  13. Checkupdate. Start ();
  14. }
  15. Private thread checkupdate = new thread (){
  16. Public void run (){
  17. Try {
  18. URL updateurl = new URL ("http://iconic.4feets.com/update ");
  19. Urlconnection conn = updateurl. openconnection ();
  20. Inputstream is = conn. getinputstream ();
  21. Bufferedinputstream Bis = new bufferedinputstream (is );
  22. Bytearraybuffer BAF = new bytearraybuffer (50 );
  23. Int current = 0;
  24. While (current = bis. Read ())! =-1 ){
  25. BAF. append (byte) Current );
  26. }
  27. /* Convert the bytes read to a string .*/
  28. Html = new string (BAF. tobytearray ());
  29. Mhandler. Post (showupdate );
  30. } Catch (exception e ){
  31. }
  32. }
  33. };
  34. Private runnable showupdate = new runnable (){
  35. Public void run (){
  36. Toast. maketext (iconic. This, "HTML code:" + HTML, Toast. length_short). Show ();
  37. }
  38. };
  39. }

Original article: http://www.androidsnippets.org/snippets/1/

 

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.