Non-Blocking Web-Request

来源:互联网 发布:域名哪家好 编辑:程序博客网 时间:2024/05/21 06:48

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/

 

原创粉丝点击