Android批量圖片載入經典系列——使用xutil架構緩衝、非同步載入網狀圖片

來源:互聯網
上載者:User

標籤:

一、問題描述

  為提高圖片載入的效率,需要對圖片的採用緩衝和非同步載入策略,編碼相對比較複雜,實際上有一些優秀的架構提供瞭解決方案,比如近期在git上比較活躍的xutil架構

  Xutil架構提供了四大模組:

1、  DbUtil模組:採用ORM機制簡化Sqlite操作,一行代碼就可執行增刪改查、支援事務、支援延遲策略

2、  ViewUtils模組:可以說是Android的IOC架構,可以註解方式對ui、資源、事件進行綁定

3、  HttpUtils模組:支援同步、非同步請求、支援大檔案上傳

4、  BitmapUtils模組:圖片的非同步載入,支援本地和網狀圖片, 圖片的壓縮處理, 圖片的記憶體緩衝以及本地檔案快取。

  本案例主要使用Xutil的HttpUtils模組和BitmapUtils模組

二、案例介紹

  實現圖片新聞瀏覽:

 

三、案例主要技術
1、使用HttpUtils模組實現網路通訊

  (1)RequestParams組件佈建要求參數、上傳檔案等資訊

RequestParams params = new RequestParams(“utf-8”); // 預設編碼UTF-8params.addQueryStringParameter("categoryId","2");//設定參數

  (2) HttpUtils組件發送請求

HttpUtils http = new HttpUtils();http.configResponseTextCharset("utf-8");// 設定返迴文本的編碼, 預設編碼UTF-8//發送請求,分別設定傳送方式、url、傳遞資料、回調組件httpUtils.send(HttpMethod.POST, "http://192.168.2.178:8080/21-sun/PhotosServlet", params,  new RequestCallBack<String>(){                            @Override                            public void onFailure(HttpException e, String m) {//執行失敗回調方法                                     Log.i("jereh", e.getExceptionCode()+" "+m);                            }                            @Overrid                            public void onSuccess(ResponseInfo<String> info) {                                     //執行成功回調方法,並傳入資料,通過info.result獲得返回資料                            }                          });
2、使用BitmapUtils圖片的非同步載入

  使用BitmapUtils圖片的非同步載入,支援本地和網狀圖片, 圖片的壓縮處理。

  (1)、BitmapDisplayConfig圖片顯示的配置

   BitmapDisplayConfig  bigPicDisplayConfig = new BitmapDisplayConfig();// 顯示原始圖片,不壓縮, 盡量不要使用, 圖片太大時容易OOM。   bigPicDisplayConfig.setShowOriginal(true);        bigPicDisplayConfig.setBitmapConfig(Bitmap.Config.RGB_565);//設定圖片的最大尺寸, 不設定時更具控制項屬性自適應displayConfig.setBitmapMaxSize(BitmapCommonUtils.getScreenSize(mActivity));//實現一個漸層動畫。    AlphaAnimation animation=new AlphaAnimation(0.1f,1.0f);    animation.setDuration(500);    displayConfig.setAnimation(animation);

       (2) 建立BitmapUtils

  構造:

/*** @param context 上下文      * @param diskCachePath  磁碟快取路徑      * @param memoryCacheSize 記憶體緩衝大小     * @param diskCacheSize 磁碟緩衝空間大小*/BitmapUtils(Context  context, String  diskCachePath, int  memoryCacheSize, int  diskCacheSize)

  其他形式

BitmapUtils(Context context)BitmapUtils(Context context, String  diskCachePath)BitmapUtils(Context  context,  String diskCachePath, int  memoryCachePercent);

  代碼:

// 擷取應用程式最大可用記憶體        int maxMemory = (int) Runtime.getRuntime().maxMemory();        int cacheSize = maxMemory / 8;        FileUtils fileUtils=new FileUtils(mActivity, "jereh");        //設定檔案快取、記憶體緩衝大小        BitmapUtils  utils=new BitmapUtils(mActivity,fileUtils.getCacheDir(),cacheSize);

  (3)display()方法非同步載入圖片並顯示到View控制項上

utils.display(T  container , String  uri,   BitmapDisplayConfig   displayConfig);
3、Gson組件實現json資料的解析
Gson gson=new Gson();//建立gson組件    //將伺服器返回的JSON資料,使用Gson解析List<ImageInfo> imageInfo=gson.fromJson(“JSON資料”, new TypeToken<ArrayList<ImageInfo>>(){}.getType());
四、案例完整代碼
1、PhotoBrowseAdapter適配器代碼
public class PhotoBrowseAdapter extends PagerAdapter {    private Activity mActivity;    private List<ImageInfo> imageList;    private LayoutInflater inflate;    private BitmapUtils utils;    private BitmapDisplayConfig displayConfig;        public PhotoBrowseAdapter(Activity mActivity, List<ImageInfo> imageList) {        super();        this.mActivity = mActivity;        this.imageList = imageList;        inflate=LayoutInflater.from(mActivity);        // 擷取應用程式最大可用記憶體        int maxMemory = (int) Runtime.getRuntime().maxMemory();        int cacheSize = maxMemory / 8;        FileUtils fileUtils=new FileUtils(mActivity, "jereh");        utils=new BitmapUtils(mActivity,fileUtils.getCacheDir(),cacheSize);        displayConfig=new BitmapDisplayConfig();        //displayConfig.setShowOriginal(true); // 顯示原始圖片,不壓縮, 盡量不要使用, 圖片太大時容易OOM。    //utils.configDefaultBitmapMaxSize(BitmapCommonUtils.getScreenSize(mActivity));        displayConfig.setBitmapMaxSize(BitmapCommonUtils.getScreenSize(mActivity));        AlphaAnimation animation=new AlphaAnimation(0.1f,1.0f);        animation.setDuration(500);        displayConfig.setAnimation(animation);    }    @Override    public int getCount() {        // TODO Auto-generated method stub        return imageList.size();    }    @Override    public boolean isViewFromObject(View arg0, Object arg1) {        // TODO Auto-generated method stub        return arg0==arg1;    }    @Override    public Object instantiateItem(View container,int position){        ImageInfo info=imageList.get(position);        LinearLayout view=(LinearLayout)inflate.inflate(R.layout.phone_item, null);        ((TextView)view.findViewById(R.id.tvTitle)).setText(info.getImgTitle());        ((TextView)view.findViewById(R.id.tvContent)).setText(info.getImgDesc());        ImageView img=(ImageView)view.findViewById(R.id.ivPhoto);        img.setTag(info.getImgUrl());        utils.display(img,info.getImgUrl(),displayConfig);        ((ViewPager)container).addView(view);        return view;    }    @Override    public void  destroyItem(View container,int position,Object obj){        ((ViewPager)container).removeView((View)obj);    }    }
2、MainActivity代碼
    public class MainActivity extends Activity {    private ViewPager vpImagePager;    private PhotoBrowseAdapter adapter;    private List<ImageInfo> imageInfoList;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        vpImagePager=(ViewPager)super.findViewById(R.id.vpImgBrowse);        imageInfoList=new ArrayList<ImageInfo>();        adapter=new PhotoBrowseAdapter(this,imageInfoList);        loadData();            }         private void loadData(){            RequestParams params=new RequestParams();        params.addQueryStringParameter("categoryId","2");//設定參數        HttpUtils httpUtils=new HttpUtils();        //向伺服器發送請求httpUtils.send(HttpMethod.POST, "http://192.168.2.178:8080/21-sun/PhotosServlet",         params,new RequestCallBack<String>(){            @Override            public void onFailure(HttpException e, String m) {                Log.i("jereh", e.getExceptionCode()+" "+m);            }            @Override            public void onSuccess(ResponseInfo<String> info) {//後台執行完成後回調,並傳入返回資料                Gson gson=new Gson();//建立gson組件                //將info.result伺服器返回的JSON資料,使用Gson解析                List<ImageInfo> imageInfo=gson.fromJson(info.result, new TypeToken<ArrayList<ImageInfo>>(){}.getType());                imageInfoList.addAll(imageInfo);                vpImagePager.setAdapter(adapter);            }            });    }}
3、ImageInfo實體類和 FileUtils工具類
//封裝圖片資訊public class ImageInfo {    private String imgUrl;    private String imgTitle;    private String imgDesc;    …//省略}FileUtils獲得檔案快取目錄public class FileUtils {    /** 快取檔案目錄 */    private File mCacheDir;     public FileUtils(Context context, String cacheDir){    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))         mCacheDir = new File(cacheDir);      else         mCacheDir = context.getCacheDir();// 如何擷取系統內建的緩衝儲存路徑      if(!mCacheDir.exists())            mCacheDir.mkdirs();    }     public String getCacheDir(){            return mCacheDir.getAbsolutePath();    }
4、服務端PhotosServlet代碼
public void doPost (HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {    response.setContentType("text/json;charset=utf-8");    String categoryId=request.getParameter("categoryId");//測試傳遞參數    System.out.println(categoryId);    List<ImagePart> partList=new ArrayList<ImagePart>();    ImagePart part1=new ImagePart();                part1.setImgUrl("http://news.21-sun.com/UserFiles/x_Image/x_20150216131001_0.jpg");    part1.setImgTitle("代表中國的東風隊,加油!");    part1.setImgDesc("...");    ImagePart part2=new ImagePart();    part2.setImgUrl("http://news.21-sun.com/UserFiles/x_Image/x_20150216131432_0.jpg");        part2.setImgTitle("三亞沃帆賽體驗之旅");        part2.setImgDesc("...");        ImagePart part3=new ImagePart();        part3.setImgUrl("http://news.21-sun.com/UserFiles/x_Image/x_20150216131157_0.jpg");        part3.setImgTitle("沃爾沃集團總裁兼首席執行官歐羅夫?佩森與沃爾沃");        part3.setImgDesc("...");        partList.add(part1);partList.add(part2);partList.add(part3);        JSONArray jsonArray=JSONArray.fromObject(partList,config);        response.getWriter().println(jsonArray.toString());    }

 

  想要瞭解更多內容的小夥伴,可以點擊查看源碼,親自運行測試。

  疑問諮詢或技術交流,請加入官方QQ群: (452379712)

 

傑瑞教育
出處:http://blog.csdn.net/jerehedu/ 
本文著作權歸煙台傑瑞教育科技有限公司和CSDN共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。 

Android批量圖片載入經典系列——使用xutil架構緩衝、非同步載入網狀圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.