80.Android in-store management

Source: Internet
Author: User

reprint: Http://www.jianshu.com/p/9fb0a795da931. Memory in Android 1.1 garbage collection mechanism in Android

The Android platform is one of the most attractive features for developers: There is a garbage collection mechanism that eliminates the need to manually manage memory, and the Android system automatically tracks all objects and frees objects that are no longer in use.

    • Young Generation Cenozoic

      1. Most new objects are located in the Eden (Eden) area
      2. When the Eden area is filled with objects, the minor GC is executed (lightweight GC). and transfer all surviving objects to one of the survivor areas.
      3. Survivor Space:s0, S1 has two, stores the object that survives after each garbage collection
      4. The Minor GC also examines the surviving objects in the survivor area and transfers them to another survivor area, so that there will always be an empty survivor area for a period of time.

    • Old Generation Laosheng Generation

      1. Storing long-lived objects and surviving objects after multiple minor GC
      2. Full major GC (heavier GC)

    • Permanent Generation Permanent Generation

    • Store the method area, in the method area, the class information to load, the static variables, the final type of constants, properties, and method information

1.2 Garbage collection
    • Too much memory to allocate space for new objects
    • Different virtual machines take different policies when GC occurs, and may halt execution of the current program
1.3 Garbage collection Mechanism &fps
    • The Android system emits vsync signals every 16ms, triggering a rendering of the UI, so the entire process is guaranteed to reach a smooth image within 16ms. 60FPS
    • If a frame's operation exceeds 16ms, it will make the user feel the Lag
    • GC occurs during UI rendering, resulting in a frame drawing time exceeding 16ms
1.4 Memory leaks

During the entire Android development process, memory leaks are an important factor in the oom (out of memory overflow)

    1. The application allocates a large number of objects that cannot be reclaimed
    2. This leads to less memory being allocated
    3. When the creation of new objects requires insufficient memory
    4. A GC is called for garbage collection when the memory is found to be insufficient
    5. The result: There will be a lag
1.5 Memory Jitter

Cause: Memory jitter is due to the fact that the application creates a large number of objects in a short period of time and is released immediately.

    1. Generating a large number of objects in an instant can seriously occupy young generation's memory area
    2. When the threshold is reached and there is not enough space left, the GC is triggered and the newly created object is quickly recycled.
    3. Instant allocation of objects consumes very little memory, and a frequency-divided GC overlay increases the heap pressure
    4. Thus triggering more other types of GC.
    5. Result: This operation has the potential to affect the frame rate and make the user aware of performance issues
2. Memory Detection Tool 2.1 memory monitor
    • Advantages
      • Easy display of memory usage and GC conditions
      • Whether the fast positioning of the stutter is related to GC
      • Quickly locate crash crashes are associated with high memory consumption
      • Quickly locate potential memory leak issues
      • Simple to use
    • Disadvantages
      • Can't pinpoint the problem correctly
2.2 Allocation Tracker Assignment Tracker
    • Advantages
      • Locate the type, size, time, thread, stack, and other information of the assigned object in the code
      • Locating memory jitter Issues
      • Locating memory leaks with Heapviewer
    • Disadvantages
      • Use complex
    • Display information for all objects (doughnut chart)
2.3 Heap Viewer Heap View
    • Advantages
      • Memory Snapshot Information
      • Collect information once per GC
      • Find a memory leak weapon
    • Disadvantages
      • Use complex
    • Displays the allocated object size information (package view)
2.4 Leak Canary

Https://github.com/square/leakcanary

  • Reference

      dependencies {      ‘com.squareup.leakcanary:leakcanary-android:1.3‘      releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.3‘  }
  • Use

      Memory Leak DetectionPrivate Refwatcher Refwatcher;PublicStatic RefwatcherGetrefwatcher (context context) {Ttapplication application = (ttapplication) context.getapplicationcontext (); return application.refwatcher;} @Override public void onCreate () {super.oncreate (), Refwatcher = Leakcanary.install (this); //detection} public void OnDestroy () {Refwatcher refwatcher = Ttapplication.getrefwatcher (Getactivity ()); Refwatcher.watch (this); //Memory leak detection}</code>               
3. Common memory leak issues 3.1 single-case leaks

Save the context object in singleton mode, the instance object itself holds a reference to a context object, and the activity is immediately destroyed and cannot be recycled because the static variable holds its reference

public class  AppManager {private static AppManager instance; private context context; private AppManager (context context" {this.context = Context;} public static AppManager getinstance (context Context) {if ( Instance! = null) {instance = new AppManager (context);} return instance; }} 

can be changed to

PublicClassappmanager {private static AppManager instance; private context context; private AppManager (context context" {//Use Application context (can also be customized application) this.context = Context.getapplicationcontext (); } public static AppManager getinstance (context Context) {if ( Instance! = null) {instance = new AppManager (context);} return instance; }} 
3.2 Leaks caused by static instances of non-static inner classes

Static Sresource will indirectly hold a reference to an mainactivity instance when it is created, causing mainactivity to not be recycled

PublicClassMainactivityextends activity {private static Span class= "Hljs-type" >testresource sresource = null;  @Override protected void OnCreate ( bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (if (Sresource = null) {Sresource = new testresource (); //...} //non-static inner class class testresource {//...}}       

Either set the inner class as a static inner class or extract the inner class to encapsulate it into a single case

Use Application context If you use the context

But dialog cannot use the context of application and service

3.3 Handler caused by memory leak problem

When an anonymous object is created, the object indirectly holds a reference to an instance of the external class, and the Mhandler object itself holds a reference to the mainactivity, causing the mainactivity to be destroyed immediately after destruction

PublicClassMainactivityextends Activity {private handler Mhandler = new handler () { @Override public void Handlemessage (message msg) {}};  @Override protected void OnCreate ( bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (private void LoadData () {//... request message Message = message.obtain (); Mhandler.sendmessage (Message);}}  

Avoid using non-static inner classes in activity, such as declaring handler as static, so that handler's survival time is irrelevant to the activity.

Introduce the weak reference into the activity, avoid the activity as the context incoming

Empty before use

PublicClassMainactivityExtendsActivity {private staticClassMyHandlerExtendsHandler {PrivateFinalweakreference<Mainactivity> mactivity;private myhandler (MainActivity Activity) {mactivity = new weakreference< mainactivity> (activity);}  @Override public void Handlemessage (message msg) {}}  @Override protected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); LoadData (); } private void LoadData () {//... request message Message = message.obtain (); Mhandler.sendmessage (Message);}}  
3.4 Collection Class leaks
    • If the collection class is a global variable (a static property in a class, a global map, such as an existing static reference, or final always points to it)
    • No corresponding removal mechanism
    • It is likely that the memory consumed by the collection will only increase
4. Ways to avoid memory leaks
    1. Try not to let static variables refer to activity
    2. Using WeakReference weak references guarantees that GC will be recycled
    3. Using static inner classes instead of inner classes, static inner classes do not hold references to external classes
    4. Static inner classes use weak references to reference external classes
    5. Releasing resources at the end of the declaration cycle
5. Reduce Memory usage
    1. Use a lighter-weight data structure (Sparearray instead of HashMap)

      • Google's own defined class takes up less memory
    2. Avoid creating objects in the OnDraw method

      • The OnDraw () method is frequently called, in which an object is created that causes too many temporary objects, and memory jitter occurs
    3. Object Pool (Message.obtain ())

      • When you must create an object in OnDraw, it is recommended that you use the object pool
      • Equivalent to object buffering, when it is created, looks for objects that already exist, and does not create
    4. LRUCache

      • Significantly reduce memory usage
    5. Bitmap memory multiplexing, compression (INSAMPLESIZE,INBITMAP)

    6. StringBuilder

      • Instead of string, especially when stitching

80.Android in-store management

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.