当前位置:   article > 正文

使用AsyncTask实现图片加载进度监听_监听async await 接口进度

监听async await 接口进度

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

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

Demo代码

  1. public class MainActivity extends AppCompatActivity {
  2. private ProgressBar mProgressBar;
  3. private ImageView mImageView;
  4. private Button mButton;
  5. private MyAsyncTask mTask;
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_main);
  10. mProgressBar = findViewById(R.id.progressBar);
  11. mImageView = findViewById(R.id.imageView);
  12. mButton = findViewById(R.id.btn);
  13. mButton.setOnClickListener(new View.OnClickListener() {
  14. @Override
  15. public void onClick(View v) {
  16. mTask = new MyAsyncTask(MainActivity.this);
  17. String url = "http://wx1.sinaimg.cn/mw600/0076BSS5ly1gbophiekmuj30u0190aiq.jpg";
  18. mTask.execute(url);
  19. }
  20. });
  21. }
  22. static class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
  23. private WeakReference<MainActivity> mWeakReference;
  24. MyAsyncTask(MainActivity activity) {
  25. mWeakReference = new WeakReference<>(activity);
  26. }
  27. //执行前的准备(UI线程)
  28. @Override
  29. protected void onPreExecute() {
  30. super.onPreExecute();
  31. }
  32. //异步执行的代码(子线程)
  33. @Override
  34. protected Bitmap doInBackground(String... strings) {
  35. String url = strings[0];
  36. HttpURLConnection connection = null;
  37. InputStream inputStream = null;
  38. OutputStream outputStream = null;
  39. File file;
  40. Bitmap bitmap = null;
  41. try {
  42. connection = (HttpURLConnection) new URL(url).openConnection();
  43. Log.i("kkk", "responseCode = " + connection.getResponseCode() + "\ncontentLength = " + connection.getContentLength());
  44. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
  45. return null;
  46. //获取文件总长度
  47. int totalLength = connection.getContentLength();
  48. int currentLength = 0;
  49. inputStream = connection.getInputStream();
  50. file = new File(mWeakReference.get().getCacheDir().getAbsolutePath() + File.separator + url.substring(url.lastIndexOf("/")));
  51. outputStream = new FileOutputStream(file);
  52. byte[] bytes = new byte[1024 * 8];
  53. int len;
  54. int percent;
  55. while ((len = inputStream.read(bytes)) != -1) {
  56. currentLength += len;
  57. percent = (int) ((float) currentLength / totalLength * 100);
  58. //缓存到本地
  59. outputStream.write(bytes, 0, len);
  60. Log.i("kkk", "percent = " + percent);
  61. publishProgress(percent);
  62. }
  63. //加载本地缓存的图片并返回
  64. bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
  65. } catch (IOException e) {
  66. e.printStackTrace();
  67. } finally {
  68. try {
  69. if (connection != null)
  70. connection.disconnect();
  71. if (inputStream != null)
  72. inputStream.close();
  73. if (outputStream != null)
  74. outputStream.close();
  75. } catch (IOException e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. return bitmap;
  80. }
  81. //执行进度(UI线程)
  82. @Override
  83. protected void onProgressUpdate(Integer... values) {
  84. mWeakReference.get().mProgressBar.setProgress(values[0]);
  85. }
  86. //执行完成返回结果(UI线程)
  87. @Override
  88. protected void onPostExecute(Bitmap bitmap) {
  89. super.onPostExecute(bitmap);
  90. if (bitmap == null)
  91. return;
  92. MainActivity activity = mWeakReference.get();
  93. activity.mButton.setVisibility(View.GONE);
  94. activity.mProgressBar.setVisibility(View.GONE);
  95. activity.mImageView.setImageBitmap(bitmap);
  96. }
  97. }
  98. @Override
  99. protected void onDestroy() {
  100. super.onDestroy();
  101. if (mTask != null && !mTask.isCancelled()) {
  102. mTask.cancel(true);
  103. }
  104. }
  105. }

完成效果

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/413601
推荐阅读
  

闽ICP备14008679号