HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Reuse a base class [Activity] handler in all sub classes for background work

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
classbackgroundallsubforreuseclassesworkactivityhandler

Problem

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?

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#105362, answer score: 6

Revisions (0)

No revisions yet.