实现下载图片显示进度条(采用asynctask)

实现下载图片带有进度条

首先看下实现的效果

这是采用异步加载的方式实现图片的下载

总体不多说啦, 贴上代码

package com.sxt.d06_asynctask.task;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

/** * 1、AsyncTask的使用必须实现的是其子类对象 * 2、参数 * 2.1 Params * 在启动AsyncTask是的传入参数 * 也是doInBackground()方法的形参 * 2.2 Progress * publishProgress()方法的传入参数 * onProgressUpdate()方法的形参 * 2.3 Result * 作为doInBackground()方法的返回值类型 * onpostExecute()方法的形参 * * 3、AsyncTask对象的使用,必须只能使用一次,如果对象已经被启动,需要被重新实例 * * 4、回调方法执行的顺序为 * 4.1 onPreExecute * 4.2 doInBackground * 4.3 onPostExecute * * 备注: publishProgress方法调用之后,onProgressUpdate才会被回调 * @author ZXY * */

public class MyTask extends AsyncTask<String, Integer, Bitmap> {

    private ImageView iv;
    private ProgressBar pb;
    private ProgressBar horPb;

    public MyTask(ImageView iv, ProgressBar pb, ProgressBar horPb) {
        this.iv = iv;
        this.pb = pb;
        this.horPb = horPb;
    }

    //该方法将会在doInBackground()方法之前被回调
    //该方法将会在主线程当中被回调
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pb.setVisibility(View.VISIBLE);
        iv.setVisibility(View.GONE);

        System.out.println("MyTask>>>onPre");
    }

    //该方法将会在子线程当中被回调
    @Override
    protected Bitmap doInBackground(String... params) {
        System.out.println("MyTask>>>doInBackground");

        try {
            URL url = new URL(params[0]);
            URLConnection conn = url.openConnection();
            int totalLen = conn.getContentLength();//总长度

            publishProgress(1, totalLen);

            InputStream is = conn.getInputStream();

            String filePath = "/mnt/sdcard/baidu.jpg";

            File tmpFile = new File(filePath);

            //如果文件不存在,则对该文件进行创建
            if (!tmpFile.exists()) {
                tmpFile.createNewFile();
            }

            //输入缓冲流
            BufferedInputStream bis = new BufferedInputStream(is);

            //输出缓冲流--将流对象写入到tmpFile文件当中
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile));

            //声明缓冲区大小(8KB)
            byte[] buf = new byte[8 * 1024];
            int len = 0;
            while((len = bis.read(buf)) != -1){
                bos.write(buf, 0, len);

                publishProgress(2, len);
            }

            bos.flush();

            bos.close();
            bis.close();

            Bitmap bmp = BitmapFactory.decodeFile(filePath);

            return bmp;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // publishProgress(1, 2, 3, 4);
        // publishProgress(1, 2, 3, 4);
        // publishProgress(1, 2, 3, 4);
        // publishProgress(1, 2, 3, 4);

        return null;
    }

    //该方法将会在publishProgress()方法被调用之后回调
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        System.out.println("MyTask>>>onProgressUpdate");

        //第一步 设置horPb的max
        if (values[0] == 1) {
            horPb.setMax(values[1]);

        }else if (values[0] == 2) {//第二部 不断更新horPb的进度
            horPb.setProgress(horPb.getProgress() + values[1]);
        }
        // horPb.setMax(max)

    }

    //该方法将会在doInBackground()方法之后被回调
    //该方法将会在主线程当中被回调
    @Override
    protected void onPostExecute(Bitmap bmp) {
        super.onPostExecute(bmp);
        System.out.println("MyTask>>>onPostExecute");

        iv.setImageBitmap(bmp);
        iv.setVisibility(View.VISIBLE);
        pb.setVisibility(View.GONE);
    }

}
package com.sxt.d06_asynctask;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.sxt.d06_asynctask.task.MyTask;

public class MainActivity extends Activity {

    private MyTask task;

    private ImageView iv;

    private ProgressBar pb;
    private ProgressBar horPb;

    private String picUrlStr = "http://www.bz55.com/uploads/allimg/150309/139-150309101F2.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.iv);

        pb = (ProgressBar) findViewById(R.id.pb);
        horPb = (ProgressBar) findViewById(R.id.horPb);



        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 实例一个新的MyTask对象
                task = new MyTask(iv, pb, horPb);
                //启动MyTask对象
                task.execute(picUrlStr);

            }
        });
    }


}

下次采用handle 的方式来实现

你可能感兴趣的:(实现下载图片显示进度条(采用asynctask))