AsyncTask下载图片带进度条

main_activity.xml布局文件:

<?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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.mrzhao.imagedemo.MainActivity">

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

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

MainActivity文件:

public class MainActivity extends AppCompatActivity {

    private String path = "http://f2.dn.anqu.com/down/ZmQ1MA==/allimg/1208/48-120PQ61324.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 MyTask().execute();

    }

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //准备工作  将 弹出框展示出来!
            dialog.show();

        }

        @Override
        protected Bitmap doInBackground(String... strings) {

            InputStream inputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(30 * 1000);
                conn.setReadTimeout(30 * 1000);
                // 获取文件总大小
                int total = 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(100);
                        //叠加计算已经下载的文件大小
                        current+=len;
                        outputStream.write(bytes, 0, len);

                        //已经下载的文件大小 除以  文件的 总大小  乘以100%   进度!
                        int progress = (int) ((current / (float)total) * 100);
                        // 更新进度
                        publishProgress(progress);

                    }
                    //将  OutputStream 转换成为数组
                    byte[] bitmapBytes = outputStream.toByteArray();
                    //将数组转换成为  图片对象
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
                    return bitmap;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

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

猜你喜欢

转载自blog.csdn.net/b892686007/article/details/80021624