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);
}
}
比较三种方法,感觉代码简洁方面用第三方法不错。