Android avoid memory leaks

What is a memory leak?

  The memory is recovered for various reasons have not been recovered, also reside in memory.

Memory leaks have any effect?

  May be a small memory leak will cause the entire application Caton, or even crash.

 

Examples:  

Toast.makeText(MainActivity.this,"Hello",Toast.LENGTH_SHORT).show();

  The code memory leaks may occur.

Why could cause a memory leak?

  If prior to the disappearance of Toast, Toast holds the current Activity, but this time, the user clicks the back button, resulting Activity can not be GC (Garbage Collection garbage collection) recovered, this Activity will cause a memory leak.

Solution?

  Current Activity and all independent Context can be passed, to avoid memory leaks using the same method elsewhere need to pass the Context. (This sentence me that they understand not) as follows

Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

   getApplicationContext () is the context of the entire application, not hold an Activity object.

 

note

  dialog context can not be used getApplicationContext (), the program will collapse out, dialog instantiated must hold the Activity object.

 

Guess you like

Origin www.cnblogs.com/xqz0618/p/11545580.html