赞
踩
AsyncTask可以用来处理一些后台较耗时的任务,查看源码发现其内部就是一个Handler和线程池的封装,因此可以帮助我们处理耗时任务的同时去更新UI。
本次内容就利用了AsyncTask去实现完成了一个简单的对图片加载进度监听的Demo,当然这个监听的实现方法有很多,也有很多开源的图片加载框架也实现了这个功能,这次就当开括思路,也算是和大家一起回顾一下AsyncTask的使用吧。
- 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);
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。