码迷,mamicode.com
首页 > 其他好文 > 详细

基于AsyncTask的图片下载

时间:2014-08-19 20:43:15      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:des   android   style   blog   http   color   java   os   

有一阵子没有写程序,连基本的AsyncTask用法都记不清楚了,复习一下于是有了下面的图片加载类。

package com.hitech.download;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoader {

    private static final String TAG = "ImageLoader";
    private String url = null;
    private ImageView imageView = null;

    public ImageLoader() {
    }

    public ImageLoader(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    public void execute() {
        new Loader().execute(new String[] { url });
    }

    public class Loader extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(params[0]);
            Log.e(TAG, params[0]);
            try {
                HttpResponse response = client.execute(request);
                System.out.println(response.getStatusLine().getStatusCode());
                if (response.getStatusLine().getStatusCode() == 200) {
                    return BitmapFactory.decodeStream(response.getEntity().getContent());
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bm) {
            super.onPostExecute(bm);
            // imageView.setImageBitmap(bm);
            imageView.setImageBitmap(bm);
        }
    }
}

调用只需要一行简单的代码就能完成图片的加载。

new ImageLoader("http://192.168.0.251/welcome.png", imageView1).execute();
new ImageLoader("http://192.168.0.251/genymotion.png", imageView2).execute();

 

基于AsyncTask的图片下载,布布扣,bubuko.com

基于AsyncTask的图片下载

标签:des   android   style   blog   http   color   java   os   

原文地址:http://www.cnblogs.com/magics/p/3922888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!