Android garbage collection solves memory leak problem _android

Source: Internet
Author: User
Tags garbage collection message queue static class

In the Android code, there are a few simple writing and coding habits that can lead to a lot of memory leaks in our code, where we make a summary of known errors:
1. The mistakes that often occur when writing a single example.

Wrong way:

 public class foo{

   private static foo foo;

   Private context Mcontext;

   Private Foo (context Mcontext) {

    this.mcontext = mcontext;

   }

   General single example, non-thread safe public

   static Foo getinstance (context mcontext) {

    if (Foo = = null)

     foo = new Foo (mcontext); 
   return foo;

   }

   public void Otheraction () {

    mcontext.xxxx ();

    ...

   }}

  

Error Reason:

If we use Foo.getinstance () in activity A or elsewhere, we will always write a "this" or "Mcontext" (this variable also points to this). Imagine that the Foo we are using is a single example, meaning that it will always be initialized and in memory so that we don't create Foo objects in the future when we call. But the "mcontext" variable in Foo has always held the "context" in activity a, causing activity A to destroy itself even if it executes the OnDestroy method. But "ApplicationContext" is different, it has been accompanied by our application exists (may be destroyed halfway, but also automatically recreate), so do not worry about "Mcontext" in Foo will hold a reference to an activity, so that it can not be destroyed.

Correct way:

 public class foo{

   private static foo foo;

   Private context Mcontext;

   Private Foo (context Mcontext) {

    this.mcontext = mcontext;

   }

   General single example, non-thread safe public

   static Foo getinstance (context mcontext) {

    if (Foo = = null)

     foo = new Foo ( Mcontext.getapplicationcontext ());

    return foo;

   }

   public void Otheraction () {

    mcontext.xxxx ();

    ...

   }}

  

  

2, the use of anonymous internal classes often occur when the error

Wrong way:

 public class Fooactivity extends activity{

   private TextView TextView;   



   Private Handler Handler = new Handler () {

    @override public

    void Handlermessage (msg) {

     

    }

   };

   @override public

   void OnCreate (Bundle Bundle) {

    super.oncreate (Bundle);

    Setcontextview (r.layout.activity_foo_layout);

    

    TextView = (TextView) Findviewbyid (R.id.textview);

    

    Handler.postdelayed (New Runnable () {

     @override public

     void Run () {

       textview.settext ("OK");

     }

    , 1000 *);

   }

  



Error Reason:

When we execute the Fooactivity finish method, the deferred message exists in the main thread message queue for 10 minutes before being processed, and the message contains a handler reference, and handler is an instance of an anonymous inner class. It holds a reference to the outside fooactivity, so this leads to fooactivity not being recycled, which in turn leads to a memory leak caused by the inability of many of the resources held by fooactivity to be recycled.

Note that the new runnable above is also implemented by anonymous inner classes, which also hold fooactivity references and prevent fooactivity from being recycled.

A static anonymous inner class instance does not hold a reference to the external class.

Correct way:

 public class Fooactivity extends activity{private TextView TextView;

   private static class MyHandler extends Handler {private final weakreference<fooactivity> mactivity;

   Public MyHandler (fooactivity activity) {mactivity = new weakreference<fooactivity> (activity);

     @Override public void Handlemessage (message msg) {fooactivity activity = mactivity.get ();

    if (activity!= null) {//...}



   } private Final MyHandler handler = new MyHandler (this);

    @override public void OnCreate (Bundle Bundle) {super.oncreate (Bundle);

    

    Setcontextview (r.layout.activity_foo_layout);

    

    TextView = (TextView) Findviewbyid (R.id.textview);

   Handler.postdelayed (New Myrunnable (TextView), 1000 * 60 * 10); private static class Myrunnable implements runnable{private weakreference<textview> Textviewweakrefere

    

    nCE Public myrunnable (TextView TextView) {teXtviewweakreference = new weakreference<textview> (TextView);

       @override public void Run () {final TextView TextView = Textviewweakreference.get ();

       if (TextView!= null) {Textview.settext ("OK");

   }

     };

  

 }

  }

3, after the use of handler, remember in the OnDestroy inside Handler.removecallbacksandmessages (object token);

 Handler.removecallbacksandmessages (null);

  Removecallbacksandmessages, when the parameter is NULL, you can clear all the handler-related runnable and message, we call the secondary method in OnDestroy does not occur memory leaks.

Points to note in development to avoid memory leaks:

    • 1. Do not allow a life cycle longer than the activity of the object to hold the reference to the activity
    • 2. Try to use the context of application rather than the context of activity
    • 3. Try not to use non-static inner classes in the activity, because non-static inner classes implicitly hold references to external class instances (specifically, you can see the private modifier for the Java: "Invalid"). If you use a static inner class, hold the external instance reference as a weak reference.
    • 4. Garbage collection does not solve the memory leak, understand the Android garbage collection mechanism

The method for getting the context, and the difference between using the context and ApplicationContext:

    • 1.view.getcontext, returns the context object for the current View object, usually the activity object that is currently being displayed.
    • 2.activity.getapplicationcontext, gets the context object for the current activity's (application) process, which is usually given priority when we use it.
    • 3,contextwrapper.getbasecontext (): Used to get a contextwrapper to decorate the context before, you can use this method, this method in the actual development of the use of not much, also do not recommend use.
    • 4.activity.this returns the current activity instance, if the UI control needs to use an activity as the context object, but the default toast actually uses ApplicationContext.

It's important to see that there are some numbers added to the No, which is actually the ability to say yes, but why is no? One of the following is an explanation:

Number 1: initiating an activity is possible in these classes, but a new task needs to be created. The general situation is not recommended.

Number 2: It is legal to layout inflate in these classes, but it will use the default theme style of the system, and if you customize some of the styles it may not be used.

Number 3: allowed when receiver is null, in 4.2 or more versions, to get the current value of the sticky broadcast. (Can be ignored)

Note: ContentProvider, Broadcastreceiver is in the table above because there is a context in its internal method for use.

Well, here we look at the table, focus on the activity and application, and see that the UI-related methods are basically not recommended or application, and the first three operations are almost impossible to appear in application. In fact, as long as you hold on to something that is relevant to the UI, you should use the activity as the context, and other operations, service,activity,application, and so on, and of course, note the holding of the case reference, Prevent memory leaks.

The above is the entire content of this article, I hope to help you learn.

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.