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.
In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context. getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.
Another easy way could be , provide public getter method in application class which returns class instance member context and the context is initialised in oncreatw method of application class of your app.
You can go for getApplicationContext() if you wanna get context of whole application. If you want to get context of current class you can use getBaseContext() instead.
getApplicationContext() - Returns the context for all activities running in application. getBaseContext() - If you want to access Context from another context within application you can access. getContext() - Returns the context view only current running activity. Save this answer.
Do this:
In the Android Manifest file, declare the following.
<application android:name="com.xyz.MyApplication"> </application>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With