老罗AsyncTask(20)带进度条下载图片例子

布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <Button android:id="@+id/download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载图片"/>
</LinearLayout>
public class MainActivity extends Activity {

    private Button mButton;
    private ImageView mImageView;
    private String path = "http://f.hiphotos.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=c8306d71f5deb48fef64a98c9176514c/0b55b319ebc4b74576634006c9fc1e178a82152e.jpg";
    private ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button)this.findViewById(R.id.download);
        mImageView = (ImageView)this.findViewById(R.id.imageView1);
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("等待下载");
        mProgressDialog.setMessage("正在下载");
        //设置等待进度条风格
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //避免点击其他位置将下载条隐藏,也就是进度条直到下载完才能消失
        mProgressDialog.setCancelable(false);
        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                MyTask task = new MyTask();
                task.execute(path);
            }
        });
    }
    private class MyTask extends AsyncTask<String, Integer, Bitmap>{
        @Override
        protected void onPreExecute() {
            mProgressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... arg0) {
            //从程序到电脑上,ByteArrayOutputStream 用于将图片读取放在内存缓冲区里
            ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
            InputStream inputStream = null;
            Bitmap bitmap = null;
            try {
                //完成对图片的下载功能
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(arg0[0]);
                HttpResponse response = client.execute(get);
                if(response.getStatusLine().getStatusCode() == 200){
                    inputStream = response.getEntity().getContent();
                    //先要获得文件的总长度
                    long fileLenth = response.getEntity().getContentLength();
                    int lenth = 0;
                    int total_lenth = 0;
                    byte[] data = new byte[1024];
                    //read(byte[] b) 从输入流中读取一定数量的字节并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数
                    while((lenth = inputStream.read(data)) != -1){
                        total_lenth += lenth;
                        //声明一个刻度
                        int values = 0;
                        values = (int) ((total_lenth / (float) fileLenth) * 100);
                        //将刻度发布出去
                        publishProgress(values);
                        //每读1024个字节放到字节流中
                        outputstream.write(data,0,lenth);
                    }
                    byte[] res = outputstream.toByteArray();
                    //将字节流转换成字节数组
                    bitmap = BitmapFactory.decodeByteArray(res, 0, res.length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return bitmap;
        }


        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            mProgressDialog.dismiss();
            mImageView.setImageBitmap(result);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgressDialog.setProgress(values[0]);
        }
    }

记得在AndroidManifest.xml文件中添加

<uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

结果:
这里写图片描述
相关参考:老罗Android(19)AsyncTask下载图片例子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值