Memory Optimization for android development-optimized memory for android development using soft references

Source: Internet
Author: User

Memory Optimization for android development-optimized memory for android development using soft references

All Android Developers must have encountered the headache of memory overflow. Once this problem occurs, it is difficult to determine whether there is a problem in our application. To locate the cause of the problem, you must use some memory analysis tools and strong experience to quickly locate the problem.

Based on this feature of mobile development, I will summarize my experience in solving this problem based on the principle of minimizing memory consumption and the memory accumulation (occasional overflow) I encountered recently.

Problem Source: when there were not so many App functions at first, I did not notice this problem. Later, the more features, the more images, I used the Allocation Tracker provided by ADT to check the memory Allocation. Obviously, many useless data objects were not released. I thought it was a universalImageLoader problem, I thought that this open-source project had a problem loading images. Later I removed all the images and looked at the memory allocation to see whether there were any data objects. It took two days to find that, some local bitmaps are not recycled and are always cached in the memory. Another reason is as mentioned in the previous article. In order to implement the exit function, A global ArrayList is used to store all newly started activities. As a result, large objects such as the Activity cannot be released. These two problems arise only when the memory is not accumulated.

After locating the problem, replace the previous solution with the broadcast method. This solves half of the problem. How can we deal with the local image? I checked some articles on the Internet and saw many great gods say soft references, So I studied how to use soft references. It is indeed a good thing to find this soft reference. It can indeed optimize the memory consumption of the entire application.

Since JDK1.2, java divides objects into four levels to achieve flexible control of the program's object financial cycle. These four levels are from strong to weak: strong references, soft references, weak reference, virtual reference. It is not much to say about strong references. It is an object we create directly at ordinary times without any modification, that is, strong references. If you have not used virtual references for the moment, you will have no in-depth understanding. The usage of weak references is basically the same as that of soft references, so I will focus on how to use soft references in applications.

If an object has only soft references, GC will not recycle the object if the memory is sufficient. If the memory is insufficient, the memory of the object with soft references will be recycled first, and ensure that the memory will not overflow. Based on this feature of soft reference, we can use soft reference to implement high-speed cache in memory sensitive areas. Therefore, to prevent memory overflow, when processing objects that occupy a large amount of memory and have a long Declaration cycle, we can try to use soft references, such as Context and its subclass objects, Drawable and its subclass objects, bitmap objects. When creating these class objects, try to declare them as soft references.

Soft reference object Declaration: SoftReference <Class> instance;

The following two examples show the actual code used in the project.

// This example is used to process large objects with long lifecycles /************************* * ********************************** @ File Name: activityManager. java * @ Creation Time: November 6, 2014 11:38:23 * @ file Description: Activity management class * @ modification history: create the initial version ************************************** on April 9, November 6, 2014 ************************************ * *******************/public class ActivityManager {private static ActivityManager manager = null; private static HashMap <String, SoftReference <Activity> activityMap; // static statement block, loaded in class Run static {manager = new ActivityManager (); activityMap = new HashMap <String, SoftReference <Activity> ();} private ActivityManager () together () {} public static ActivityManager getInstance () {return manager;} public void put (Activity act) {activityMap. put (act. toString (), new SoftReference <Activity> (act);} public void remove (Activity act) {activityMap. remove (act. toString ();} public void finishAllActivity () {Set <Str Ing> set = activityMap. keySet (); Iterator <String> iter = set. iterator (); while (iter. hasNext () {String actName = iter. next (); Activity currentAct = activityMap. get (actName ). get (); if (currentAct! = Null) {currentAct. finish (); currentAct = null ;}} activityMap. clear (); activityMap = null ;}}

// This example is used to process memory-sensitive objects such as Bitmap. Example public class BitmapManager {private static BitmapManager bitmapManager = null; private static HashMap <String, SoftReference <Bitmap> imageCache = null; static {bitmapManager = new BitmapManager (); imageCache = new HashMap <String, SoftReference <Bitmap> ();} private BitmapManager () {} public static BitmapManager getInstance () {return bitmapManager;} public static void saveBitmapToCache (String path) {Bitmap bitmap = BitmapFactory. decodeFile (path); // Add the soft reference object to Map to cache imageCache. put (path, new SoftReference <Bitmap> (bitmap); // after use, manually set the Bitmap object to nullbitmap = null;} public static Bitmap queryBitmapByPath (String path) {// retrieve SoftReference <Bitmap> softBitmap = imageCache. get (path); // You must judge whether soft references are recycled. if (softBitmap = null) {return null;} Bitmap bitmap = softBitmap is returned when being recycled. get (); return bitmap ;}}
Conclusion: when developing an application, it is best to take into account possible problems at the beginning of implementation. We should handle these issues carefully in advance and prevent such problems from occurring at the root, when the problem occurs, it will take more effort to deal with it.

 


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.