Android 網路訪問 線程注意事項

來源:互聯網
上載者:User

類比一個 從網路中讀取一個圖片展示到imageView的操作:

注意事項1:

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

執行此方法用來開闢一個URL請求,該請求在Android4.0版本以後需要放到子線程中實現,主線程已不支援httprequest請求(android2.3仍然支援此項)

InputStream inputStream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// iv.setImageBitmap(bitmap);

第三句則會報錯 :android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

注意事項2: 因為在子線程中不可以對view操作,因為view是在主線程建立的,需要在子線程中以訊息的形式通知主線程

new Thread(){public void run(){try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Shuame)");int responseCode = conn.getResponseCode();if(responseCode==200){InputStream inputStream = conn.getInputStream();Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//iv.setImageBitmap(bitmap);
                                         //採用傳送訊息的模式 把view操作訊息發給主線程Message msg = new Message();msg.what=CHANGE_UI;msg.obj=bitmap;handler.sendMessage(msg);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();Toast.makeText(MainActivity.this, "訪問網路失敗",0).show();}}}.start();
主activity中定義handler:

private Handler handler =new Handler(){public void handleMessage(android.os.Message msg){if(msg.what==CHANGE_UI){iv.setImageBitmap((Bitmap) msg.obj);}};};



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.