Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 622
Andrea Baccega Avatar asked Jan 04 '10 21:01

Andrea Baccega


People also ask

How do you get the context of a static method?

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.

How do you pass a static class context?

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.

How do I find application context?

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.

What is the difference between getContext () getApplicationContext () getBaseContext () and this?

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.


1 Answers

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.

like image 146
Rohit Ghatol Avatar answered Oct 02 '22 19:10

Rohit Ghatol