Get Current Activity Context in a non activity class

18,866

You can use Application class :

public class MyApplication extends Application {
private static Context context;
private static Activity activity;

public void onCreate() {
    super.onCreate();
    MyApplication.context = getApplicationContext();
}

public synchronized static Context getAppContext() {
    return MyApplication.context;
}

/**
 * setCurrentActivity(null) in onPause() on each activity 
 * setCurrentActivity(this) in onResume() on each activity
 * 
 */

public static void setCurrentActivity(Activity currentActivity) {
    activity = currentActivity;
}

public static Activity currentActivity() {
    return activity;
}

}
Share:
18,866

Related videos on Youtube

Mukesh Kumar Singh
Author by

Mukesh Kumar Singh

fun getDeveloper(): Developer { val me = Developer() me.name = "Mukesh" me.dob = "03-05-1986" me.platform = "Android" me.primaryLanguage = "Java" me.otherLanguage = "Kotlin" me.email = "[email protected]" return me } Programeers Always think like this

Updated on September 15, 2022

Comments

  • Mukesh Kumar Singh
    Mukesh Kumar Singh almost 2 years

    I have an application in android which has no. of activity. Now I needed that the context of currently running activity in a non-activity class. How can I get that.

  • marciowb
    marciowb over 10 years
    This "solution" is introducing several bugs in your application, including: memory leak and wrong references. Always take the control to the current activity. There are many techniques to track activity transitions (or fragments transactions). The main problem here is because you are using static variables to hold instances that you know that will be invalid at any time.
  • Abdullah
    Abdullah over 10 years
    That's why I wrote a comment in the code saying set current activity to null in onPause and set it again in onResume
  • Sagar Trehan
    Sagar Trehan about 9 years
    I thinks this solution is valid. Anybody else try it and getting issues with this solution.
  • inquisitive
    inquisitive about 9 years
    without changing the code in the activity how do we get the current running activity in the application?
  • authentictech
    authentictech about 5 years
    What about when you are already extending a class (like ContentProvider)?