Singleton with context in Android

I want to create a Singleton class that will be callable from all points in my application. The problem is this class will need a context for its operations.

I don’t want to have to recreate the singleton in every activity because that way it looses all sense, so I thought about creating it in my MainActivity, with an init method where I pass the context as an argument. From that point on, my Singleton would be useable, but I think this is bad design because that way my MainActivity reference will always be held and thus I might run into memory leaks.

  • How to access views from view pager
  • Unable to link native library in OpenCV Android sample
  • Problems importing project into Android Studio regarding ActionBarSherlock
  • Select text from TextView?
  • Android ADT 21.0 warning: Implicitly using the default locale
  • Tiled background is pushing it's View size
  • Am I right here?

    Related posts:

    Kitkat, error while trying to load an image
    Qt Android: Why is a QtApp-debug.apk created for a Release build?
    How to use SearchView from dark theme in Light Appcompat theme
    Enum vs. Static Constants, memory footprint
    Android MediaPlayer get volume
    Bounce button on tap
  • Set a time-out for android requestSingleUpdate
  • Android Studio Stuck at Gradle Download on create new project
  • Android CPU ARM architectures
  • Android Floating Action Button API 19 (KitKat)
  • Apache HTTP Client Removal from API23, will that have an effect on Volley?
  • Android CalendarView class cannot be found
  • One Solution collect form web for “Singleton with context in Android”

    You are right not to save main activity context into the singleton because of memory leaks. If you need constant context inside your singleton, use getApplicationContext(). This can be safely saved. Note though that this context is not useable for most gui-related functions. In rare cases you need activity level context inside singleton, pass calling activity context to singleton’s method without saving

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.