Memory leakage caused by Handler

Source: Internet
Author: User

First look at a set of simple code

 
 
  1. public class SampleActivity extends Activity { 
  2.  
  3.   private final Handler mHandler = new Handler() { 
  4.     @Override 
  5.     public void handleMessage(Message msg) { 
  6.       // ...  
  7.     } 
  8.   } 
  9.   

When we writeActivityMedium,Android LintWill prompt us suchWarning: In Android, Handler classes should be static or leaks might occur..
Meaning:In Android, the Handler class should be static; otherwise, leakage may occur.

Why?

Learn moreHandler

What causes memory leakage? Let's look at the following code.

 
 
  1. Public class SampleActivity extends Activity {
  2.  
  3. Private final Handler mHandler = new Handler (){
  4. @ Override
  5. Public void handleMessage (Message msg ){
  6. //...
  7. }
  8. }
  9.  
  10. @ Override
  11. Protected void onCreate (Bundle savedInstanceState ){
  12. Super. onCreate (savedInstanceState );
  13.  
  14. // Send a message that is executed 10 minutes later
  15. MHandler. postDelayed (new Runnable (){
  16. @ Override
  17. Public void run (){}
  18. },600000 );
  19.  
  20. // End the current Activity
  21. Finish ();
  22. }
  23. }

WhenActivityAfterMessage queueProcess thisMessagePreviously, it will survive. ThisMessageHoldHandlerAndHandlerYesActivity(SampleActivity) reference, thisActivityAll resources cannot be recycled before message processing, So memory leakage occurs.

The solution is as follows:

 
 
  1. Public class SampleActivity extends Activity {
  2.  
  3. /**
  4. * Using static internal classes does not hold the reference of the current object
  5. */
  6. Private static class MyHandler extends Handler {
  7. Private final WeakReference <SampleActivity> mActivity;
  8.  
  9. Public MyHandler (SampleActivity activity ){
  10. MActivity = new WeakReference <SampleActivity> (activity );
  11. }
  12.  
  13. @ Override
  14. Public void handleMessage (Message msg ){
  15. SampleActivity activity = mActivity. get ();
  16. If (activity! = Null ){
  17. //...
  18. }
  19. }
  20. }
  21.  
  22. Private final MyHandler mHandler = new MyHandler (this );
  23.  
  24. /**
  25. * Using static internal classes does not hold the reference of the current object
  26. */
  27. Private static final Runnable sRunnable = new Runnable (){
  28. @ Override
  29. Public void run (){}
  30. };
  31.  
  32. @ Override
  33. Protected void onCreate (Bundle savedInstanceState ){
  34. Super. onCreate (savedInstanceState );
  35.  
  36. // Send a message that is executed 10 minutes later
  37. MHandler. postDelayed (sRunnable, 600000 );
  38.  
  39. // End
  40. Finish ();
  41. }
  42. }

OK, end

NOTE:Many people worry about weak references.ActivityWe don't have to worry about recycling, because in this interfaceActivityIt won't be recycled. Think about it.If our Activity is recycled, how does this interface exist?

NOTE2:Ladies and gentlemen, referAsyncTask. Check the document and your own understanding. I still hope you will forgive me for any errors.

NOTE3:I am not clear about how to prevent leaks,HandlerBelow is a piece of source code

 
 
  1. final Class<? extends Handler> klass = getClass(); 
  2.             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 
  3.                     (klass.getModifiers() & Modifier.STATIC) == 0) { 
  4.                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " + 
  5.                     klass.getCanonicalName()); 
  6.             } 
  7.   

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.