代码改变世界

【android】从网络获取图片的三种方法

2012-08-09 21:09  Loull  阅读(567)  评论(0编辑  收藏  举报

http://blog.csdn.net/ameyume/article/details/6089334

以上链接:实现图片的放大缩小

http://blog.csdn.net/kesenhoo/article/details/6534757

以上链接:用另一种思路实现~~~(改天认真读一下)

http://doinone.iteye.com/blog/1074283

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);
        }
}

比较三种方法,感觉代码简洁方面用第三方法不错。