Android: Calling non-static methods from a static Handler class

前端 未结 3 406
醉酒成梦
醉酒成梦 2021-02-06 02:47

Given this code:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

public static final int MESSAGE_NOT_CONNECTED = 1;

@Over         


        
相关标签:
3条回答
  • 2021-02-06 03:32

    In my activity's onDestroy method I call:

    this.myHandler.removeCallbacksAndMessages(null);
    

    This does not get rid of the "This Handler class should be static or leaks might occur" warning, but I believe it destroys the message hence stopping the leak. My handler class is an inner non-static class of my activity. My activity has an instance of MyHandler myHandler.

    When I do this, the handler's handleMessage method isn't called, which I assume means that the message containing the handler, which contained a reference to the activity was destroyed. Am open for comments as I haven't tested it with any leak testing tools. Here is where I copied the idea: http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html answerer: CyrilJanuary 15, 2013 at 7:50 AM

    0 讨论(0)
  • 2021-02-06 03:49

    Try using a WeakReference, as described in this article.

    0 讨论(0)
  • 2021-02-06 03:49

    Since you are now using a WeakReference, mTarget.get() might return null. In your edited code, you are not checking if target is null before executing target.setStatus(R.string.title_not_connected). So this may throw a NullPointerException if the weakreference object has been GC'ed.

    0 讨论(0)
提交回复
热议问题