How to reference the current or main activity from another class

AndroidDev picture AndroidDev · Jun 27, 2012 · Viewed 93k times · Source

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?

Answer

Alessandro Muzzi picture Alessandro Muzzi · Jan 22, 2015

If you already have a valid context, just use this: Activity activity = (Activity) context;