android中擷取網狀圖片是一件耗時的操作,如果直接擷取有可能會出現應用程式無響應(ANR:Application Not Responding)對話方塊的情況。對於這種情況,一般的方法就是耗時操作用線程來實現。下面列三種擷取url圖片的方法:
1.直接擷取:(容易:ANR,不建議)
mImageView = (ImageView)this.findViewById(R.id.imageThreadConcept) ;
Drawable drawable = loadImageFromNetwork(IMAGE_URL);
mImageView.setImageDrawable(drawable) ;
公用方法:
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 ;
}
2. 後台線程擷取url圖片:
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);
}
}