Android_ Performance Optimization Viewpager loading hundreds of millions of HD large-picture Oom solutions

Source: Internet
Author: User

I. Background

Recently done projects need to select Image upload, similar to, Weibo-like image selector, contentresolver read local image resources and recyclerview+glide loading picture display on the list display, this is no big problem, the point is, Click on the image to go to large map, such as your album has hundreds of pictures, it means that in the Viewpager need to load hundreds of view, and the mobile phone photos are 1-2 pixels of the high-resolution large image (the author's 20 million Pixels of the picture 3888*5152), Size also has 5-7 trillion, viewpager slide not more than 10 on the oom, that is, the picture has been compressed processing, the image resolution to 1366*960, size compression to less than 150k, And in the Viewpager of the Destroyitem method to do bitmap resource recovery, although the effect is better, this also can not withstand the advent of oom (on-line search scheme are compressed, using third-party controls, recycling, in fact, this is useless, Maybe they have not really experienced viewpager load hundreds of thousand Zhang Datu feelings), browse to the 第50-70 Zhang when the oom memory has been soaring, the fundamental recovery, do not believe you try, compression and recovery can not cure the problem, then how to solve it? Research and Weibo, how they will not oom, and finally I think of a solution.

II. Implementation of the programme1. Common practice in the past

Part of the code:

list<subsamplingscaleimageview> mviews = new arraylist<> ();                int size = Mdatas.size ();        for (int i = 0; i < size; i++) {            Subsamplingscaleimageview view = new Subsamplingscaleimageview (this);            Mviews.add (view);        }        MBinding.viewpager.setAdapter (New Myadapter ());

Class Myadapter extends Pageradapter {@Override public int getcount () {return mdatas.size (); } @Override Public Boolean isviewfromobject (view view, Object object) {return view = = Obje        Ct } @Override Public Object instantiateitem (ViewGroup container, final int position) {viewgroup.la Youtparams params = new Viewgroup.layoutparams (viewpager.layoutparams.match_parent,viewpager.layoutpar Ams.            Match_parent);            Final Subsamplingscaleimageview ImageView = mviews.get (position);            Imageview.setlayoutparams (params);            Final String url = mdatas.get (position);            String cacheexists = cacheexists (URL);                    if (Textutils.isempty (cacheexists)) {//No cache required compression (compression time-consuming async) New asynctask<void, Void, string> () { @Override protected string Doinbackground (Void ... voids) {string CA CheNoexistspath = Getcachenoexistspath (URL);                        Bitmapcompressutils.compressbitmap (URL, cachenoexistspath);                        File File = new file (Cachenoexistspath);                        if (file.exists ()) {//presence indicates successful return cachenoexistspath;                        } else {return URL;                        }} @Override protected void OnPostExecute (String s) {                    Imageview.setimage (Imagesource.uri (s));            }}.execute ();            } else {//There is a cache directly showing Imageview.setimage (Imagesource.uri (cacheexists));            } container.addview (ImageView);        return imageView; } @Override public void Destroyitem (ViewGroup container, int position, object object) {Subsampli            Ngscaleimageview ImageView = mviews.get (position); if (ImageView! = nulL) {imageview.recycle ();        } container.removeview (ImageView); }    }

/** * Determine the current picture URL corresponds The compressed cache exists "" means that there is no * * @param url picture path * @return */private string cacheexists (String URL) {TR            y {file Filedir = new File (Mcacherootpath);            if (!filedir.exists ()) {filedir.mkdirs (); } File File = new file (mcacherootpath,new StringBuffer (). Append (md5encryptorutils.md5encryption (URL)). toString (            ));            if (file.exists ()) {return File.getabsolutepath ();        }} catch (Exception e) {e.printstacktrace ();    } return "";        } public string Getcachenoexistspath (string url) {File Filedir = new File (Mcacherootpath);        if (!filedir.exists ()) {filedir.mkdirs (); } return new StringBuffer (). Append (Mcacherootpath). Append (md5encryptorutils.md5encryption (URL)). ToS    Tring (); }

Can see, here the author through their own compression algorithm (the previous article ANDROID_NDK image compression Libjpeg library use) to do a picture compression, and cache, attentive friends should have found Mviews collection add the number of view is Mdatas size, This will cause a problem viewpager has been sliding down the time, memory has been increased, that is, to do a resource recovery, but also does not solve the problem(moreover the author here shows the picture the control is subsamplingscaleimageview very good big picture local loading control can effectively prevent the Oom), you can try, a large number of images will still be oom, this is rooted in the Viewpager loaded picture number problem.



2. Solution:

Image compression has been done, resource recycling has been done, but viewpager loading more and more pictures of the time will oom you can not avoid, do not believe you try;

Here is to use the Viewpager view of the reuse mechanism (self-understanding), that is, mviews we fixed a given number, such as 4, so that the viewpager I actually need the item is only 4.

Modified part of the code:


for (int i = 0; i < 4; i++) {            Subsamplingscaleimageview view = new Subsamplingscaleimageview (this);            Mviews.add (view);        }        MBinding.viewpager.setAdapter (New Myadapter ());

Class Myadapter extends Pageradapter {@Override public int getcount () {return mdatas.size (); } @Override Public Boolean isviewfromobject (view view, Object object) {return view = = Obje        Ct } @Override Public Object instantiateitem (ViewGroup container, final int position) {viewgroup.la Youtparams params = new Viewgroup.layoutparams (viewpager.layoutparams.match_parent,viewpager.layoutpar Ams.            Match_parent);            int i = position% 4;            Final Subsamplingscaleimageview ImageView = Mviews.get (i);            Imageview.setlayoutparams (params);            Final String url = mdatas.get (position);            String cacheexists = cacheexists (URL);                    if (Textutils.isempty (cacheexists)) {//No cache required compression (compression time-consuming async) New asynctask<void, Void, string> () {          @Override protected String doinbackground (Void ... voids) {              String Cachenoexistspath = Getcachenoexistspath (URL);                        Bitmapcompressutils.compressbitmap (URL, cachenoexistspath);                        File File = new file (Cachenoexistspath);                        if (file.exists ()) {//presence indicates successful return cachenoexistspath;                        } else {return URL;                        }} @Override protected void OnPostExecute (String s) {                    Imageview.setimage (Imagesource.uri (s));            }}.execute ();            } else {//There is a cache directly showing Imageview.setimage (Imagesource.uri (cacheexists));            } container.addview (ImageView);        return imageView; } @Override public void Destroyitem (ViewGroup container, int position, object object) {int i = P            Osition% 4; Subsamplingscaleimageview imageView = Mviews.get (i);            if (ImageView! = null) {imageview.recycle ();        } container.removeview (ImageView); }

A simple modification can effectively prevent Oom from using position%4 to get the number of controls from Mviews, ensuring that the Viewpager loaded mviews storage image is 4

Look at the memory charts that have been sliding down



The memory basically remains stable

Three, demo demo

Because you want to read the album, no longer the simulator runs the recording GIF, directly


Demo Download: http://download.csdn.net/detail/hqiong208/9723673

Iv. Summary

This is just a simple demonstration, the actual project in the album more complex than this, simply said to be compressed, to recycle, view reuse.

Can you leave a message?







Android_ Performance Optimization Viewpager loading hundreds of millions of HD large-picture Oom solutions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.