URL轉Drawable之 Android中獲取網路圖片的三種方法
阿新 • • 發佈:2019-02-10
轉載自: http://doinone.iteye.com/blog/1074283
android中獲取網路圖片是一件耗時的操作,如果直接獲取有可能會出現應用程式無響應(ANR:Application Not Responding)對話方塊的情況。對於這種情況,一般的方法就是耗時操作用執行緒來實現。下面列三種獲取url圖片的方法:
1.直接獲取:(容易:ANR,不建議)
mImageView = (ImageView)this.findViewById(R.id.imageThreadConcept) ; Drawable drawable = loadImageFromNetwork(IMAGE_URL); mImageView.setImageDrawable(drawable) ;
公用方法:
2. 後臺執行緒獲取url圖片:private Drawable loadImageFromNetwork(String imageUrl) { Drawable drawable = null; try { // 可以在這裡通過檔名來判斷,是否本地有此圖片 drawable = Drawable.createFromStream( new URL(imageUrl).openStream(), "image.jpg"); } catch (IOException e) { Log.d("test", e.getMessage()); } if (drawable == null) { Log.d("test", "null drawable"); } else { Log.d("test", "not null drawable"); } return drawable ; }
mImageView = (ImageView)this.findViewById(R.id.imageThreadConcept) ; new Thread(new Runnable(){ Drawable drawable = loadImageFromNetwork(IMAGE_URL); @Override public void run() { // post() 特別關鍵,就是到UI主執行緒去更新圖片 mImageView.post(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub mImageView.setImageDrawable(drawable) ; }}) ; } }).start() ;
3.AsyncTask獲取url圖片
mImageView = (ImageView)this.findViewById(R.id.imageThreadConcept) ;
new DownloadImageTask().execute(IMAGE_URL) ;
private class DownloadImageTask extends AsyncTask<String, Void, Drawable>
{
protected Drawable doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Drawable result) {
mImageView.setImageDrawable(result);
}
}