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

Given this code:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener { public static final int MESSAGE_NOT_CONNECTED = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); } // ------------------------------------------------- public final void setStatus(int Rid) { final ActionBar actionBar = getActionBar(); actionBar.setSubtitle(Rid); } // ------------------------------------------------- static Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_NOT_CONNECTED: setStatus(R.string.title_not_connected); break; } } } } 

I get a compilation error: I can not make a static reference to the non-static setStatus (int) method ...

This makes sense because getActionBar () in setStatus () is a non-stationary method.

I made the Handler class static due to a warning: this handler class must be static or a leak may occur.

Question: how to correctly access the setStatus () method from a static handler?

EDIT: The new handler code is the answer.

 static class hHandler extends Handler { private final WeakReference<MainActivity> mTarget; hHandler(MainActivity target) { mTarget = new WeakReference<MainActivity>(target); } @Override public void handleMessage(Message msg) { MainActivity target = mTarget.get(); If(target == null) { return; } switch (msg.what) { case MESSAGE_NOT_CONNECTED: target.setStatus(R.string.title_not_connected); break; } } } 
+8
android handler android-actionbar
source share
3 answers

Try using WeakReference as described in the article .

+9
source share

Since you are using WeakReference , mTarget.get() may return null . In the edited code, you do not check if the target null before executing target.setStatus(R.string.title_not_connected) . Thus, this can raise a NullPointerException if the weakreference object was GC'ed.

+1
source share

In my work onDestroy method I call:

 this.myHandler.removeCallbacksAndMessages(null); 

This will not save you from the fact that "this handler class must be static or may occur", but I believe that it destroys the message, thereby stopping the leak. The handler class is an internal non-static class of my activity. My activity has an instance of MyHandler myHandler.

When I do this, the handleMessage method of the handler is not called, and I assume that the message containing the handler containing the link to the action has been destroyed. I am open to comment since I have not tested it with any leak testing tools. This is where I copied this idea: http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html defendant: Cyril January 15, 2013 at 7:50

0
source share

All Articles