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.
- Import java. Io. bufferedinputstream;
- Import java. Io. inputstream;
- Import java.net. url;
- Import java.net. urlconnection;
- Import org. Apache. http. util. bytearraybuffer;
- Public class iconic extends activity {
- Private string html = "";
- Private handler mhandler;
- Public void oncreate (bundle savedinstancestate ){
- Super. oncreate (savedinstancestate );
- Setcontentview (R. layout. Main );
- Mhandler = new handler ();
- Checkupdate. Start ();
- }
- Private thread checkupdate = new thread (){
- Public void run (){
- Try {
- URL updateurl = new URL ("http://iconic.4feets.com/update ");
- Urlconnection conn = updateurl. openconnection ();
- Inputstream is = conn. getinputstream ();
- Bufferedinputstream Bis = new bufferedinputstream (is );
- Bytearraybuffer BAF = new bytearraybuffer (50 );
- Int current = 0;
- While (current = bis. Read ())! =-1 ){
- BAF. append (byte) Current );
- }
- /* Convert the bytes read to a string .*/
- Html = new string (BAF. tobytearray ());
- Mhandler. Post (showupdate );
- } Catch (exception e ){
- }
- }
- };
- Private runnable showupdate = new runnable (){
- Public void run (){
- Toast. maketext (iconic. This, "HTML code:" + HTML, Toast. length_short). Show ();
- }
- };
- }
Original article: http://www.androidsnippets.org/snippets/1/