In recent work, there have been several memory optimization problems, 1. After the app exits, the application process keeps a lot of memory from being freed, and the tool forces the GC to not release. 2. The application enters some pages in an instant request to allocate too much memory. These two issues are easy for experienced developers to guess is a memory leak, a resource problem such as a picture. Let's write an example to analyze these two problems.
The first example is the app that volley loads pictures, and when this app exits the cache releases the issue
Application class
Package Demo.memory.com.memorydemo;import Android.app.application;import Com.android.volley.requestqueue;import Com.android.volley.toolbox.volley;public class MyApplication extends application{ requestqueue mRequestQueue; private static MyApplication minstance; public static MyApplication getinstance () { return minstance; } @Override public void OnCreate () { super.oncreate (); Minstance = this; } Public Requestqueue Getrequestqueue () { if (mrequestqueue = = null) { mrequestqueue = Volley.newrequestqueue ( this); } return mrequestqueue;} }
The main activity simple jump function
Package Demo.memory.com.memorydemo;import Android.content.intent;import android.support.v7.app.AppCompatActivity; Import Android.os.bundle;import Android.view.view;public class Mainactivity extends Appcompatactivity { @Override protected void OnCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); } public void jump (view view) { Intent Intent = new Intent (this,showimageactivity.class); StartActivity (intent); }}
Activity that loads pictures
Package Demo.memory.com.memorydemo;import Android.app.activity;import Android.os.bundle;import Android.widget.imageview;import Com.android.volley.toolbox.imageloader;public class ShowImageActivity extends activity{private final static String Image1_url = "http://o6lxzg30h.bkt.clouddn.com/7375cd24ee25d29c81dff09a7375fff1 . jpg "; Private final static String Image2_url = "Http://o6lxzg30h.bkt.clouddn.com/223412884cpmc7m4j1gof1.jpg"; Imageloader Mimageloader; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.show_image); Mimageloader = new Imageloader (Myapplication.getinstance (). Getrequestqueue (), myimagecache.getinstance ()); ImageView Image1iv = (ImageView) Findviewbyid (R.ID.IMAGE1_IV); ImageView Image2iv = (ImageView) Findviewbyid (R.ID.IMAGE2_IV); Mimageloader.get (image1_url,new Myimagelistener (IMAGE1IV)); Mimageloader.get (Image2_url,new Myimagelistener (imAGE2IV)); }}
Other tool classes
Package Demo.memory.com.memorydemo;import Android.graphics.bitmap;import Android.util.lrucache;import Com.android.volley.toolbox.imageloader;public class Myimagecache implements Imageloader.imagecache {private LruCache <string, bitmap> Mmemorycache; private static Myimagecache Mimagecache; Private Myimagecache () {int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024); int cacheSize = MAXMEMORY/8; Mmemorycache = new lrucache<string, bitmap> (cacheSize) {@Override protected int sizeOf (String Key, Bitmap Bitmap) {return bitmap.getbytecount ()/1024; } }; } public static Myimagecache getinstance () {if (Mimagecache = = null) Mimagecache = new Myimagecache ( ); return mimagecache; } @Override public void Putbitmap (String key, Bitmap value) {mmemorycache.put (key, value); } @Override Public Bitmap getbitmap (String key) {RETUrn Mmemorycache.get (key); } public void ClearCache () {if (Mmemorycache! = null) {Mmemorycache.evictall (); } }}
Package Demo.memory.com.memorydemo;import Android.widget.imageview;import Com.android.volley.volleyerror;import Com.android.volley.toolbox.imageloader;public class Myimagelistener implements Imageloader.imagelistener { Private ImageView view; Public Myimagelistener (ImageView view) { This.view = view; } @Override public void Onerrorresponse (Volleyerror error) {} @Override the public void Onresponse ( Imageloader.imagecontainer response, Boolean isimmediate) { view.setimagebitmap (Response.getbitmap ());} }
Launch the Application interface
The app process consumes 10M of memory at this time
Quit the app, click to make a mandatory GC collection, but found that the app exited, but also occupy 9 m of memory, we know an empty application process if not killed, it takes up about 1.4M of memory is normal, now 9M is obviously a problem. Next, use the tool to analyze the problem.
The information in the heap is crawled first, because the memory footprint in Java is primarily in the heap. Click to crawl, wait a few 10 seconds, waiting for the crawl to complete will generate a hprof file, in Android Studio in the captures option folder can be seen, this file will be opened automatically by Android studio
Retained size means the total memory consumption, you can see byte[] occupy more than 8M, from this size we can probably guess this is the problem, click Byte[], from the right side of the instance can find two very large objects,
Both objects occupy 4 m of memory, click on one of the objects, in the preference tree below we can locate the Mmemorycache members of the Com.memorydemo.MyImageCache class, which seems to be the problem of this class, As we can see from the above code, Mmemorycache is a picture cache object that we define, why can't it be recycled by GC? is because it is static.
Another ancient artifact mat to analyze, Mat http://www.eclipse.org/mat/downloads.php
Mat Start Screen
This tool is read Hprof file, and the same as above, but Android studio generated is not the standard need to convert a bit, in captures right-click to select Export to Standard.hprof
The converted file, which can be recognized by Mat, opens the converted file in the mat file->open Heap dump, selects leak Suspects report, enters the interface
We click this button to generate a histogram,
Can see the same byte[] occupy high, right byte[],--> List objects--with incoming references
It is visible that the first two objects are too high, right-click one of the objects---Path to GC Roots---Exclude all phantom/weak/soft etc. references, enter the following interface point to open the call stack Discovery final positioning to MIM Agecache, this object has a small yellow dot in front of it, indicating that it cannot be recycled by GC, which says it is a static member
Well, with these two tools, it's clear that when the app exits, it's still not releasing memory because our picture cache is not released, so when did we release the image cache? After all the UI of the program is exited. Android provides the public void Ontrimmemory (Int. level) method to listen to this process, in https://developer.android.com/training/articles/ The Release memory as memory becomes tight in the memory.html documentation explains the use of each parameter of this method, and here we only have a level = Trim_memory_ui_hidden case, which indicates that the AP P all interfaces are not visible, overriding methods in the application class Ontrimmemory releasing the cache file
@Override public void Ontrimmemory (int.) { super.ontrimmemory (level); if (level = = Trim_memory_ui_hidden) { myimagecache.getinstance (). ClearCache ();} }
When the app exits, the app process takes up the memory value and returns to its normal state.
Demo code Download http://download.csdn.net/detail/u011291205/9621303
Next to illustrate a memory leak problem
Android Memory optimization problems encountered at work (1)