手记

【安卓必学-异步加载】课程对应的源码

1.MainActivity
public class MainActivity extends Activity {

    private ListView listView;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);      

        String url = "http://www.imooc.com/api/teacher?type=4&num=30";

        new mAsyncTask().execute(url);

    }

    private List<ItemBean> getJsonData(String url){

        List<ItemBean> jsonList = new ArrayList<ItemBean>();
        try {
            InputStream is = new URL(url).openStream();
            String jsonString = readStream(is);

            JSONObject object = new JSONObject(jsonString);
            JSONArray arr = object.getJSONArray("data");
            ItemBean mItemBean;
            for(int i=0;i<arr.length();i++){
                JSONObject object2 = arr.getJSONObject(i);
                mItemBean = new ItemBean();
                mItemBean.imageUrl = object2.getString("picSmall");
                mItemBean.title = object2.getString("name");
                mItemBean.content = object2.getString("description");
                jsonList.add(mItemBean);
            }
            return jsonList;

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private String readStream(InputStream is){

        try {
            InputStreamReader isr = new InputStreamReader(is,"gbk");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String str;
            while((str=br.readLine())!=null){
                sb.append(str);
            }
            isr.close();
            br.close();
            is.close();

            return sb.toString();

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    public class mAsyncTask extends AsyncTask<String, Void, List<ItemBean>>{

        @Override
        protected List<ItemBean> doInBackground(String... params) {

            return getJsonData(params[0]);
        }

        @Override
        protected void onPostExecute(List<ItemBean> result) {

             ListView_Adapter mAdapter = new ListView_Adapter(result,MainActivity.this,listView);
             listView.setAdapter(mAdapter);

             super.onPostExecute(result);
        }

    }

}
2.ItemBean
public class ItemBean {

    public String imageUrl;
    public String title;
    public String content;
}
3.ListView_Adapter
public class ListView_Adapter extends BaseAdapter implements OnScrollListener{

    private List<ItemBean> itemList;    

    private LayoutInflater inflator;
    private ImageLoader imageLoader;

    public static String[] URLS;

    private int mStart,mEnd;
    private boolean firstInTag = true;

    public ListView_Adapter(List<ItemBean> itemList,Context context,ListView listView) {
        this.itemList = itemList;   

        inflator = LayoutInflater.from(context);
        imageLoader = new ImageLoader(listView);

        URLS = new String[itemList.size()];
        for(int i=0;i<itemList.size();i++){
            URLS[i] = itemList.get(i).imageUrl;
        }

        listView.setOnScrollListener(this);
    }

    @Override
    public int getCount() {

        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if(convertView==null){
            holder = new ViewHolder();
            convertView = inflator.inflate(R.layout.item_layout, null);
            holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
            holder.content = (TextView) convertView.findViewById(R.id.text_content);
            holder.title = (TextView) convertView.findViewById(R.id.text_title);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        holder.imageView.setImageResource(R.drawable.ic_launcher);

        holder.imageView.setTag(itemList.get(position).imageUrl);

        //new ImageLoader().showImageByThread(holder.imageView, itemList.get(position).imageUrl);
        //imageLoader.showImageByAsyncTask(holder.imageView, itemList.get(position).imageUrl);

        holder.title.setText(itemList.get(position).title);
        holder.content.setText(itemList.get(position).content);

        return convertView;
    }

    class ViewHolder{
        private ImageView imageView;
        private TextView title;
        private TextView content;               
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {

        mStart = firstVisibleItem;
        mEnd = firstVisibleItem+visibleItemCount;
        if(firstInTag&&visibleItemCount>0){
            imageLoader.loadImage(mStart, mEnd);
            firstInTag = false;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        if(scrollState==SCROLL_STATE_IDLE){ //没有滚动
            imageLoader.loadImage(mStart, mEnd);
        }else{ //滚动中
            imageLoader.cancelAllTasks();
        }
    }

}
4.ImageLoader
public class ImageLoader {

    private LruCache<String, Bitmap> mCache;
    private ListView mListView;
    private Set<LoadImageTask> mTasks;

    public ImageLoader(ListView listView){

        mListView = listView;

        mTasks = new HashSet<ImageLoader.LoadImageTask>();
        //获取最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory/4;

        mCache = new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //返回图片大小,每次存入缓存时调用
                return value.getByteCount();
            };
        };
    }

    public void addBitmapToCache(String url,Bitmap bm){     
            mCache.put(url,bm); 

            if(getBitmapFromCache(url)!=null){
                System.out.println("添加");
            }
    }

    public Bitmap getBitmapFromCache(String url){
        return mCache.get(url);
    }

    public void showImageByThread(ImageView imageView, String url){

        final String imageUrl = url;
        final ImageView mImageView = imageView;

        final Handler mHandler = new Handler(){
            public void handleMessage(android.os.Message msg) {
                if(mImageView.getTag().equals(imageUrl)){
                    mImageView.setImageBitmap((Bitmap) msg.obj);
                }
            };
        };

        new Thread(){
            @Override
            public void run() {
                Bitmap bm = getBitmapFromUrl(imageUrl);
                Message message = new Message();
                message.obj = bm;               
                mHandler.sendMessage(message);
                super.run();
            }
        }.start();
    }

    public void showImageByAsyncTask(ImageView imageView, String url){

        Bitmap bm = getBitmapFromCache(url);
        if(bm==null){
            System.out.println(1);
            //new LoadImageTask(imageView,url).execute(url);
        }else{          
            imageView.setImageBitmap(bm);
        }       

    }

    public void loadImage(int start, int end){

        for(int i=start;i<end;i++){
            String url = ListView_Adapter.URLS[i];
            Bitmap bm = getBitmapFromCache(url);
            if(bm==null){
                LoadImageTask loadImageTask = new LoadImageTask(url);
                loadImageTask.execute(url);
                mTasks.add(loadImageTask);
            }else{

                ImageView imageView = (ImageView) mListView.findViewWithTag(url);
                imageView.setImageBitmap(bm);               
            }
        }
    }

    public void cancelAllTasks(){
        if(mTasks!=null){
            for(LoadImageTask loadImageTask:mTasks){
                loadImageTask.cancel(true);
            }
        }
    }

    private class LoadImageTask extends AsyncTask<String, Void, Bitmap>{

        private String url;

        public LoadImageTask(String url) {
            super();

            this.url = url;
        }

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

            Bitmap bm = getBitmapFromUrl(params[0]);
            if(bm!=null){               
                addBitmapToCache(params[0], bm);
            }
            return bm;
        }

        @Override
        protected void onPostExecute(Bitmap result) {           
            super.onPostExecute(result);
            ImageView mImageView = (ImageView) mListView.findViewWithTag(url);
            if(mImageView!=null&&result!=null){             
                mImageView.setImageBitmap(result);
            }
            mTasks.remove(this);
        }

    }

    public Bitmap getBitmapFromUrl(String url){

        try {
            InputStream is = new URL(url).openConnection().getInputStream();

            Bitmap bm = BitmapFactory.decodeStream(is);
            is.close();
            return bm;          

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}
7人推荐
随时随地看视频
慕课网APP