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;
}
}
Related videos on Youtube
![Mukesh Kumar Singh](https://i.stack.imgur.com/cPNcX.jpg?s=256&g=1)
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, 2022Comments
-
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 over 10 yearsThis "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 over 10 yearsThat'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 about 9 yearsI thinks this solution is valid. Anybody else try it and getting issues with this solution.
-
inquisitive about 9 yearswithout changing the code in the activity how do we get the current running activity in the application?
-
authentictech about 5 yearsWhat about when you are already extending a class (like ContentProvider)?