實現下載圖片顯示進度條(採用asynctask)

實現下載圖片帶有進度條

首先看下實現的效果
小的demo實現的效果

這是採用異步加載的方式實現圖片的下載

總體不多說啦, 貼上代碼

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 的方式來實現

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章