Android 實如今線程中聯網

其實咱們要牢記的是,對數據流的操做都是阻塞的,在通常狀況下,咱們是不須要考慮這個問題的,可是在Android 實現聯網的時候,咱們必須考慮到這個問題。好比:從網絡上下載一張圖片:

Java代碼:
  1. public Bitmap returnBitmap(String url)
  2. {
  3. URL myFileUrl = null;
  4. Bitmap bitmap = null;
  5. try{
  6. myFileUrl = new URL(url);
  7. }catch(MalformedURLException e){
  8. e.printStackTrace();
  9. return null;
  10. };
  11. try{
  12. HttpURLConnection conn = (HttpURLConnection)myFileUrl.openConnection();
  13. conn.setDoInput(true);
  14. conn.connect();
  15. InputStream is = conn.getInputStream();
  16. bitmap = BitmapFactroy.decodeStream(is);
  17. is.close();
  18. }catch(IOException e){
  19. e.printStackTrace();
  20. }
  21. return bitmap;
  22. }
複製代碼

                 因爲網絡鏈接須要很長的時間,須要3-5秒,甚至更長的時間才能返回頁面的內容。若是此鏈接動做直接在主線程,也就是UI線程中處理,會發生什麼情 況呢? 整個程序處於等待狀態,界面彷佛是「死」掉了。爲了解決這個問題,必須把這個任務放置到單獨線程中運行,避免阻塞UI線程,這樣就不會對主線程有任何影 響。舉個例子以下:

Java代碼:
  1. private void connect(String strURL){
  2. new Thread() {
  3. public void run() {
  4. try {
  5. HttpClient client = new DefaultHttpClient();
  6. // params[0]表明鏈接的url
  7. HttpGet get = new HttpGet(url.getText().toString());
  8. HttpResponse response = client.execute(get);
  9. HttpEntity entity = response.getEntity();
  10. long length = entity.getContentLength();
  11. InputStream is = entity.getContent();
  12. String s = null;
  13. if (is != null) {
  14. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  15. byte[] buf = new byte[128];
  16. int ch = -1;
  17. int count = 0;
  18. while ((ch = is.read(buf)) != -1) {
  19. baos.write(buf, 0, ch);
  20. count += ch;
  21. }
  22. s = new String(baos.toByteArray());
  23. Log.V(「moandroid sample」,s);
  24. }
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }.start();
  30. }
複製代碼

                使用Handler更新界面

                 如何將下載的信息顯示在界面上了,好比說下載的進度。Android SDK平臺只容許在主線程中調用相關View的方法來更新界面。若是返回結果在新線程中得到,那麼必須藉助Handler來更新界面。爲此,在界面 Activity中建立一個Handler對象,並在handleMessage()中更新UI

Java代碼:
  1. //Task在另外的線程執行,不能直接在Task中更新UI,所以建立了Handler
  2. private Handler handler = new Handler() {
  3. @Override
  4. public void handleMessage(Message msg) {
  5. String m = (String) msg.obj;
  6. message.setText(m);
  7. }
  8. }; 

  9. //只須要將上面的
  10. Log.V(「moandroid sample」,s); 

  11. //替換爲:
  12. s = new String(baos.toByteArray());
  13. Message mg = Message.obtain();
  14. mg.obj = s;
  15. handler.sendMessage(mg);
相關文章
相關標籤/搜索