Wednesday, November 13, 2019

Static way to get 'Context' in Android?



Is there a way to get the current Context instance inside a static method?



I'm looking for that way because I hate saving the 'Context' instance each time it changes.


Answer



Do this:



In the Android Manifest file, declare the following.









Then write the class:



public class MyApplication extends Application {


private static Context context;

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

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

}


Now everywhere call MyApplication.getAppContext() to get your application context statically.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...