AsyncTask异步加载问题

一、简介

    AsyncTask是一个异步的过程,有时为避免耗时操作,消耗用户的等待时间,可以将之放在异步过程中,这样一来,也可以在子线程中更新主UI,避免了阻塞。也就是说,通过此类,可以实现UI线程和后台线程进行通讯,后台线程执行异步任务,并把结果返回给UI线程.

二、主要函数

    在AsyncTask的源码中,对于AsyncTAsk的解释如下:

<p>An asynchronous task is defined by a computation that runs on a background thread and
* whose result is published on the UI thread. An asynchronous task is defined by 3 generic
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
* and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
* <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>

格式为 public abstract class AsyncTask<Params, Progress, Result> 因为是抽象类,所以只能被继承

所以在继承AsyncTask时,需要传入三个参数:

  • Params:启动任务时输入的参数类型.
  • Progress:后台任务执行中返回进度值的类型.
  • Result:后台任务执行完成后返回结果的类型.

有如下几个方法:

  •  protected void onPreExecute():在耗时任务开始之前执行,做准备工作
  • doInBackground():执行耗时任务
  • onPostExecute():耗时操作执行后执行,一般是用来UI更新
  • execute():一般在主线程中进行调用,进行耗时操作

三、实例

最近在做拍照上传的功能,但是拍照的图片内存太大了,需要进行图片压缩操作,如果把压缩操作放在主线程中,会出现用户等待的情况,所以把他放到异步进程中,并用一个PrograssBar 转圈圈

1、布局是一个ListView,里面的item是ImageView,用来展示图片,在ImageView的位置放一个PrograssBar,用来压缩图片的时候转圈圈,表示正在进行处理,开始时将其设置成不可见:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical"
    android:orientation="horizontal">

   <RelativeLayout
       android:layout_width="@dimen/distance_80dp"
       android:layout_height="@dimen/distance_85dp">

       <RelativeLayout
           android:id="@+id/rl_show_photo"
           android:layout_width="@dimen/distance_80dp"
           android:layout_height="@dimen/distance_85dp">

           <ImageView
               android:id="@+id/iv_photo"
               android:scaleType="centerCrop"
               android:layout_width="@dimen/distance_75dp"
               android:layout_height="@dimen/distance_80dp"
               android:layout_marginTop="@dimen/distance_5dp"
               android:layout_marginRight="@dimen/distance_5dp"/>
           <ProgressBar
               android:id="@+id/progress_bar_upload"
               android:layout_width="@dimen/distance_30dp"
               android:layout_height="@dimen/distance_30dp"
               android:layout_centerInParent="true"
               android:visibility="gone"/>

    
       </RelativeLayout>

2、适配器Adapter使其继承 BaseAdapter,在getView中进行对item布局中的控件进行操作,具体的其他操作就不多写,只写与AsyncTask有关的操作:

(1)写一个  getThumbnailAsyncTask类继承  AsyncTask:

class getThumbnailAsyncTask extends AsyncTask<Bitmap,Void,Bitmap> {
        private ViewHolder holder;
        private int position;
        public getThumbnailAsyncTask(ViewHolder viewHolder,int pos) {
            holder=viewHolder;
            position=pos;
        }

        @Override
        protected void onPreExecute() {
            Log.i(TAG,"onPreExecute");
            super.onPreExecute();
            //PrograssBar设置成可见
            holder.pbUpload.setVisibility(View.VISIBLE);
        }

        @Override
        protected Bitmap doInBackground(Bitmap... bitmaps) {
            Log.i(TAG,"doInBackground: ");
            Bitmap photobitmap = null;
            //压缩图片操作
            photobitmap = ImageUtils.compressBySampleSize(bitmaps[0],
                    SizeUtils.dp2px(75), SizeUtils.dp2px(80));
            return photobitmap;
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //执行完后,PrograssBar设置成不可见
            holder.pbUpload.setVisibility(View.GONE);      
            holder.ivPhoto.setImageBitmap(bitmap);
        }
    }

(2)主线程用execute()调用:

new getThumbnailAsyncTask(holder,position).execute(mPhotoList.get(position));

mPhotoList.get(position)就是doInBackground()中所需的参数Bitmap

3、问题:

使用上述方法发现每次上传多张图片时,总会重复对前面的图片进行压缩,解决办法是  可以定义一个HashMap,其键用唯一能代表此图片的uri来表示,值就是每张图片压缩后对应的bitMap:

private Map<Uri,Bitmap> photoMap=new HashMap<>();

protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //执行完后,PrograssBar设置成不可见
            holder.pbUpload.setVisibility(View.GONE);
            if (mUriList.size()>0) photoMap.put(mUriList.get(position),bitmap);
            holder.ivPhoto.setImageBitmap(bitmap);
            
        }

调用之前先判断HashMap中是否有该图片的uri,如果有则表示压缩过了,直接展示,没有再执行压缩操作

//防止item的重复加载
            if (photoMap.containsKey(mUriList.get(position))){
                holder.ivPhoto.setImageBitmap(photoMap.get(mUriList.get(position)));
            }else {
                new getThumbnailAsyncTask(holder,position).execute(mPhotoList.get(position));
            }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值