采用handle 实现下载图片带有进度条

这是采用handle+thread 实现图片的下载

不多说首先贴上效果图



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.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

/**
 * Handler来实现进度条
 * @author ZXY
 *
 */
public class MainActivity extends Activity {


    private ImageView iv;
    private ProgressBar pb;

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

    private Handler handler = new Handler(){

        //在主线程当中被回调
        public void handleMessage(android.os.Message msg) {

            if (msg.what == 0) {//设置ProgressBar的max
                Bundle data = msg.getData();
                pb.setMax(data.getInt("max"));
            }else if (msg.what == 1) {//增加ProgressBar的进度
                Bundle data = msg.getData();
                pb.setProgress(pb.getProgress() + data.getInt("progress"));

            }else if (msg.what == 2) {//显示图片资源

                iv.setImageBitmap((Bitmap) msg.obj);
            }


        };

    };


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

        iv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {

                    @Override
                    public void run() {

                        try {
                            URL url = new URL(urlStr);
                            URLConnection conn = url.openConnection();
                            //获取资源的总大小
                            int totalLen = conn.getContentLength();

                            Message maxMsg = new Message();
                            maxMsg.what = 0;

                            Bundle maxData = new Bundle();
                            maxData.putInt("max", totalLen);
                            maxMsg.setData(maxData);

                            handler.sendMessage(maxMsg);

                            InputStream is = conn.getInputStream();
                            //声明缓冲区大小(8kb)
                            byte[] buf = new byte[1024 * 8];

                            File file = new File("/mnt/sdcard/fengjing.jpg");

                            //如果图片不存在,则创建一个新的文件
                            if (!file.exists()) {
                                file.createNewFile();
                            }

                            //声明缓冲输出流
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            //声明缓冲输入流
                            BufferedInputStream bis = new BufferedInputStream(is);


                            int len = 0;//每次真实读取的长度
                            while((len = bis.read(buf)) != -1){
                                bos.write(buf, 0, len);

                                Message progressMsg = new Message();

                                progressMsg.what = 1;

                                Bundle progressData = new Bundle();
                                progressData.putInt("progress", len);

                                progressMsg.setData(progressData);


                                handler.sendMessage(progressMsg);

                            }


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

                            Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());

                            Message bmpMsg = new Message();
                            bmpMsg.what = 2;
                            bmpMsg.obj = bmp;

                            handler.sendMessage(bmpMsg);



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


                    }
                }).start();

            }
        });


    }


}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ProgressBar
        android:id="@+id/pb"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值