使用AsyncTask实现图片加载进度监听

AsyncTask可以用来处理一些后台较耗时的任务,查看源码发现其内部就是一个Handler和线程池的封装,因此可以帮助我们处理耗时任务的同时去更新UI。

本次内容就利用了AsyncTask去实现完成了一个简单的对图片加载进度监听的Demo,当然这个监听的实现方法有很多,也有很多开源的图片加载框架也实现了这个功能,这次就当开括思路,也算是和大家一起回顾一下AsyncTask的使用吧。

Demo代码

public class MainActivity extends AppCompatActivity {

    private ProgressBar mProgressBar;
    private ImageView mImageView;
    private Button mButton;
    private MyAsyncTask mTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mProgressBar = findViewById(R.id.progressBar);
        mImageView = findViewById(R.id.imageView);
        mButton = findViewById(R.id.btn);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTask = new MyAsyncTask(MainActivity.this);
                String url = "http://wx1.sinaimg.cn/mw600/0076BSS5ly1gbophiekmuj30u0190aiq.jpg";
                mTask.execute(url);
            }
        });
    }

    static class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {

        private WeakReference<MainActivity> mWeakReference;

        MyAsyncTask(MainActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        //执行前的准备(UI线程)
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //异步执行的代码(子线程)
        @Override
        protected Bitmap doInBackground(String... strings) {

            String url = strings[0];
            HttpURLConnection connection = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            File file;
            Bitmap bitmap = null;
            try {
                connection = (HttpURLConnection) new URL(url).openConnection();
                Log.i("kkk", "responseCode = " + connection.getResponseCode() + "\ncontentLength = " + connection.getContentLength());
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                    return null;
                //获取文件总长度
                int totalLength = connection.getContentLength();
                int currentLength = 0;
                inputStream = connection.getInputStream();
                file = new File(mWeakReference.get().getCacheDir().getAbsolutePath() + File.separator + url.substring(url.lastIndexOf("/")));
                outputStream = new FileOutputStream(file);
                byte[] bytes = new byte[1024 * 8];
                int len;
                int percent;

                while ((len = inputStream.read(bytes)) != -1) {
                    currentLength += len;
                    percent = (int) ((float) currentLength / totalLength * 100);
                    //缓存到本地
                    outputStream.write(bytes, 0, len);
                    Log.i("kkk", "percent = " + percent);
                    publishProgress(percent);
                }
                //加载本地缓存的图片并返回
                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (connection != null)
                        connection.disconnect();
                    if (inputStream != null)
                        inputStream.close();
                    if (outputStream != null)
                        outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

        //执行进度(UI线程)
        @Override
        protected void onProgressUpdate(Integer... values) {
            mWeakReference.get().mProgressBar.setProgress(values[0]);
        }

        //执行完成返回结果(UI线程)
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap == null)
                return;
            MainActivity activity = mWeakReference.get();
            activity.mButton.setVisibility(View.GONE);
            activity.mProgressBar.setVisibility(View.GONE);
            activity.mImageView.setImageBitmap(bitmap);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTask != null && !mTask.isCancelled()) {
            mTask.cancel(true);
        }
    }
}

完成效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值