Non-Blocking Web-Request

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.   
  7. public class Iconic extends Activity {  
  8.     private String html = "";  
  9.     private Handler mHandler;  
  10.   
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.         mHandler = new Handler();  
  15.         checkUpdate.start();  
  16.     }  
  17.   
  18.     private Thread checkUpdate = new Thread() {  
  19.         public void run() {  
  20.             try {  
  21.                 URL updateURL = new URL("http://iconic.4feets.com/update");  
  22.                 URLConnection conn = updateURL.openConnection();  
  23.                 InputStream is = conn.getInputStream();  
  24.                 BufferedInputStream bis = new BufferedInputStream(is);  
  25.                 ByteArrayBuffer baf = new ByteArrayBuffer(50);  
  26.   
  27.                 int current = 0;  
  28.                 while((current = bis.read()) != -1){  
  29.                     baf.append((byte)current);  
  30.                 }  
  31.   
  32.                 /* Convert the Bytes read to a String. */  
  33.                 html = new String(baf.toByteArray());  
  34.                 mHandler.post(showUpdate);  
  35.             } catch (Exception e) {  
  36.             }  
  37.         }  
  38.     };  
  39.   
  40.     private Runnable showUpdate = new Runnable(){  
  41.         public void run(){  
  42.             Toast.makeText(Iconic.this"HTML Code: " + html, Toast.LENGTH_SHORT).show();  
  43.         }  
  44.     };  
  45. }  

原文:http://www.androidsnippets.org/snippets/1/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值