异步加载网络图片带进度

今天要做的一个效果是,异步加载网络图片,带加载进度,先来看看效果图
这里写图片描述


大体效果就是这样,加载网络图片,并且带有一个加载进度,这个加载进度想怎么用的行,用processbar也行。那好, 我们先来看看具体的实现方式。

加载图片

首先需要知道怎么获取图片,首先获取图片是个网络操作,当然要放到异步线程里面,所以AsyncTask当然就要用到了,那么网络访问自然就要靠HttpURLConnection,获取一个流什么的,接下来就要用到BitmapFactory了,把流转化为一个Bitmap。

获取进度

首先我们需要知道怎么获取下载进度,总得知道个图片大小什么的吧,获取资源大小的方式:

    URL url = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // 文件总长度
    int contentLength = conn.getContentLength();

这样我们就获取到了文件的总大小了,接下来我们再来想办法获取进度。我们总会在读取资源流的时候,用一个while循环,每次循环都能得到当时的下载量,所以,我们需要设置一个变量来保存此次循环的总下载量,这样就能获取到当前下载的百分比了。
具体做法:

    InputStream inputStream = conn.getInputStream();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte[] data = new byte[1024];
    // 当前下载总量
    int total_length = 0;

    int len = 0;

    while ((len = inputStream.read(data)) != -1) {
        total_length += len;
        int progress_value = (int) ((total_length / (float) contentLength) * 100);
        outputStream.write(data, 0, len);
    }

现在我们就能够获取到当前进度了。

异步加载

我把所有异步加载的代码都贴出来,大家应该都能看懂

private class ImageLoaderAsyncTask extends AsyncTask<String, Integer, Bitmap> {

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

            HttpURLConnection conn = null;
            byte[] result = null;
            try {

                URL url = new URL(strings[0]);
                conn = (HttpURLConnection) url.openConnection();

                // 文件总长度
                int contentLength = conn.getContentLength();

                InputStream inputStream = conn.getInputStream();

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                byte[] data = new byte[1024];
                int total_length = 0;

                int len = 0;

                while ((len = inputStream.read(data)) != -1) {
                    total_length += len;
                    // 刷新界面
                    publishProgress(progress_value);
                    outputStream.write(data, 0, len);
                }

                result = outputStream.toByteArray();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (conn != null)
                    conn.disconnect();
            }

            return BitmapFactory.decodeByteArray(result, 0, result.length);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            img.setImageBitmap(bitmap);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            process.setText("下载进度:" + values[0] + "%");
        }

    }

源码下载:http://download.csdn.net/detail/it_xf/9701599

猜你喜欢

转载自blog.csdn.net/it_xf/article/details/53456741