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 refere开发者_如何学JAVAnce 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
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.
You're correct that many Android operations require an Activity
or (more usually) just a Context
. Provided your utility classes aren't holding onto references beyond the lifecycle of the Context
, then you should be fine.
I would shy away from a singleton referring to your 'start' Activity, since the first Activity of your app may be destroyed even if a subsequent Activity is active and visible.
An alternative approach may be to implement your own abstract class (e.g. BaseActivity
) implementing or wrapping the functionality of your utility class that all your other Activities inherit from, rather than Activity
directly. This way you can keep the plumbing away from the logic of your main activities.
精彩评论