要注意的問題:1.android4.0後,代碼不能卸載ui。
2.想想,就是通過url取網狀圖片嘛,我直接給他一個url好了嘛,然後它就給我取出來。 這邊分享一個比較簡潔的實現方式:
private class DownLoadImage extends AsyncTask {ImageSwitcher imageSwitcher;public DownLoadImage(ImageSwitcher is) { this.imageSwitcher = is; } protected Bitmap doInBackground(String... urls) { System.out.println("非同步載入圖片開始!"); String url =urls[0];//"http://ww3.sinaimg.cn/bmiddle/6e91531djw1e8l3c7wo7xj20f00qo755.jpg"; System.out.println(url); Bitmap tmpBitmap = null; try { InputStream is = new java.net.URL(url).openStream(); tmpBitmap = BitmapFactory.decodeStream(is); is.close(); } catch (Exception e) { e.printStackTrace(); Log.i("KK下載圖片", e.getMessage()); } return tmpBitmap; } @Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values); System.out.println("進程進度:"+values);}protected void onPostExecute(Bitmap result) { //TODO: //把bitmap轉drawable Resources res=getResources(); Drawable bd=new BitmapDrawable(res,result); imageSwitcher.setImageDrawable(bd); System.out.println("非同步載入圖片完成!"); } }
再在ui線程中調用 new DownLoadImage(switcher).execute(img_url);就可以啦。 函數裡的ImageSwitcher imageSwitcher;可以換成imageview或者其他控制項
上面的方法讀取圖片也就用到這兩行
InputStream is = new java.net.URL(url).openStream(); tmpBitmap = BitmapFactory.decodeStream(is);
很簡潔,可是問題來了: 我想搞個進度條來顯示圖片下載的進度,這個inputstream好像過度封裝了。
這讓我想起了那張陰陽圖,可能要實現進度條,我就要回去用代碼量比較多的方法,懂得朋友留個言哈!