Search code examples
androidandroid-activitylifecycle

Getting activity from utility classes


I have a common problem in my application where I extract functionality into classes that handles this functionality, and nothing else. The problem is that I often need an instance of an Activity for much of this functionality, like reading files, access to the database etc etc, so I have to pass the current activity to the utility and that make the code ugly.

Now I'm looking into setting up a singleton that holds a reference to my "start"-activity and then inject this Singleton into my utillites. But, and this is the but, I don't control if an activity is removed or still active, Android does. So my Activity might not be enough alive to be usable anymore.

So, to conclude, I don't feel confident that it is safe to store the reference to an activity and I don't want to pass the current activity with every call. What is the solution. Am I paranoid? :-)

Thanks in advance Roland


Solution

  • Don't store references to activities. You can use the application context instead: there is only one, and it is guaranteed to be available as long as your app is alive. For easier access you might want to define an Application class and add a getInstance() method to it. The problem with this approach is that not all operations that require a context can be performed using the application context. Anything related to views is likely to fail.