异步任务下载图片带进度条

网络权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.mrzhao.asynctaskhttpdemo.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="点击下载图片" />

    <ImageView
        android:id="@+id/show_iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity文件:

/**
 * 带有进度条的 点击启动异步任务
 */
public class MainActivity extends AppCompatActivity {
    //图片地址
    private String image_path = "http://e.hiphotos.baidu.com/zhidao/pic/item/7dd98d1001e939010d25f7727aec54e736d19652.jpg";
    //显示图片的视图
    private ImageView showIv;
    //进度条弹出框
    private ProgressDialog dialog;

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

        showIv = (ImageView) findViewById(R.id.show_iv);
        //设置进度弹出框的属性
        dialog = new ProgressDialog(this);
        //设置最大值
        dialog.setMax(100);
        //设置标题
        dialog.setTitle("提示");
        //设置显示的信息
        dialog.setMessage("亲、正在玩命儿加载...请稍后...");
        //设置弹出框为水平进度加载模式
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    }

    public void onClick(View view) {
        //点击下载图片
        new ImageDownLoadTask().execute(image_path);
    }

    //下载图片的异步任务
    class ImageDownLoadTask extends AsyncTask<String, Integer, Bitmap> {

        //下载图片前的准备工作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //准备开始下载 弹出  弹出框 显示进度
            dialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            InputStream inputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                URL url = new URL(params[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(30 * 1000);
                conn.setConnectTimeout(30 * 1000);
                //获取即将下载的文件总大小
                int contentLength = conn.getContentLength();
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    inputStream = conn.getInputStream();
                    outputStream = new ByteArrayOutputStream();
                    int len = 0;
                    //定义变量记录已经下载的文件大小
                    int current = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = inputStream.read(bytes)) != -1) {

                        Thread.sleep(50);

                        outputStream.write(bytes, 0, len);
                        //叠加进度大小
                        current += len;
                        //获取进度
                        int  progress = (int) ((current / (float)contentLength) * 100);
                        //调用该方法执行进度更新
                        publishProgress(progress);
                    }
                    byte[] bitmapByte = outputStream.toByteArray();
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapByte, 0, bitmapByte.length);
                    return bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if (inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream!=null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


            return null;
        }

        /**
         * 已下载除以 总大小 × 100  = 下载百分比
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //设置进度
            dialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //下载完成 关闭弹出框
            dialog.dismiss();
            if (bitmap != null) {
                showIv.setImageBitmap(bitmap);
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值