I am writing an android app with multiple activities. The app needs to check-in with a server when the app is 'resumed' (be it fresh start, from locked screen or switching from a different app etc.). In other words, same stuff needs to go into onResume() of all activities.
The check-in involves launch of an AsyncTask and prompting for username/password etc. if the check-in fails.
I have things working by keeping identical onResume() method on each activity (i.e. check-in code is replicated in all activities). Surely there is a better way to do this. What is it?
It depends on your use case. If all your activities require the same functionality, you can create a base activity. All your activities will extend it. Move this logic into base activity's
onResume() and then all your activities will have this logic.
If that approach doesn't work, you can try moving this logic into a separate controller class, and then use it in all activities that need it. This is a bit more flexible and will help you to avoid code duplication.