Search code examples
javaandroidandroid-activityextend

Android Java: best practice for common code in overrides for all Activities


I'm not entirely sure whether the following approach is a good or terrible one. It would be great if someone more experienced could add his/her 2 cents :)

I have an app with lots of Activities. In this case all of them must be able to receive messages from a dynamically registered receiver (in onCreate/Resume/Pause....) using LocalBroadcastManager and run an AsnycTask to do some work and display a ProgressDialog. The code needed (Receiver and AsnycTask) is absolutely the same for all Activities.

The messages can be sent at any time by one of the services.

To do that I created an Activity which implements all that (registers and unregisters the receiver in oncreate/pause/resume et.c. and contains this AsyncTask)

All other Activities should extend this Activity so I don't need to worry about putting extra code into all of their respective onCreate/onResume/onPause methods to call any helper classes/methods (and forgetting to do so).

Is this approach ok? I ask because I once stumbled upon a similar question about extending Activities from a custom class (regretfully I can't find it anymore) and one answer suggested that it would cause massive memory leaks without explaning why.

Thank you very much!


Solution

  • I've had a lot of success using a BaseActivity class that all other Activities in my project extend from. I've yet to encounter any memory issues due to this.

    An alternative approach would be putting your common functionality in Interfaces, then having your Activities implement these as necessary. There's some really good discussion of the merits of these two approaches here: Interface vs Base class