類比一個 從網路中讀取一個圖片展示到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);}};};