3
\$\begingroup\$

We are using the Thread of a common base class but using its handler in all its sub classes. The code is working fine but is it the right way to go about?

Our base class looks like this:

public class BaseActivity extends AppCompatActivity {
    public Handler mHandler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Try to reuse the activity handler. If null, create new.
        mHandler = getWindow().getDecorView().getHandler();
        if (mHandler == null) {
            mHandler = new Handler();
            Log.w(TAG, "failed to reuse activity handler");
        }
    }
}

And we are using this instance of handler in all the activities which extend from BaseActivity. We have not faced any issues. No task in the sub classes is very long. Could this be done any better?

\$\endgroup\$

2 Answers 2

6
\$\begingroup\$

You make some assumptions about your window in this line:

mHandler = getWindow().getDecorView().getHandler();

As mentioned by the Activity docs for getWindow()

Returns
Window The current window, or null if the activity is not visual

Okay. NullPointerException number 1 waiting to happen. Interestingly #getDecorView() seems to be guaranteed to not return null, which is good. One place less where this can fail.

It is irrelevant whether the returned handler is null or not, because luckily that's what this is about.


Other nitpicks:

  • Don't use Hungarian notation. mHandler should be just handler. Your IDE is perfectly capable of telling you that handler is a member of type Handler
  • Failing to reuse an activity handler is not something I'd categorize as Warning.
  • The comment you place there is partly restating the obvious. Drop the second sentence.
\$\endgroup\$
1
  • \$\begingroup\$ Any insights on anonymous inner classes holding reference of surrounding activity, preventing them from getting garbage collected. Activities are large objects in Android. \$\endgroup\$
    – divyenduz
    Sep 22, 2015 at 18:17
0
\$\begingroup\$

I found this thread because I had a problem with getWindow().getDecorView().getHandler() returning null, despite tips seen various places on the Internet that this is a good way to avoid having to create a new Handler object. After much testing I've come to the conclusion that this trick never works in an onCreate() method, nor in any of the activity startup life-cycle methods. It only works after the view has actually been made visible on the display.

So you can probably simply replace your entire method body with this:

   mHandler = new Handler(Looper.getMainLooper());
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.