Android Basic Understanding of Context
Android Basic Understanding of Context
Context allows access to application-specific resources and classes, as well as calls for
application-level operations such as launching activities, broadcasting and receiving intents, etc.
A Context represents your environment. It represents the state surrounding where you are in
your system.
An Android app has activities. Context is like a handle to the environment your application is
currently running in. The activity object inherits the Context object.
getContext(): Returns the context within the currently active Activity. You can also use
this for inflating layouts and menus, register context menus, instantiating widgets, start
other activities, create new Intent within an Activity etc.
Example: View.getContext() returns the Context the view is currently running in. Usually the
currently active Activity.
Or,
getApplicationContext(): Returns the Context for the entire application, instead of the
current Activity i.e. if you need a Context tied to the lifecycle of the entire application,
not just the current Activity. This Context is widely used as it is safest to use as this
Context exists for the lifespan of the application.
getBaseContext(): Returns a Context from another context within application that you
can access. This method has a limited usage.The method is relevant when you have a
ContextWrapper.
ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to
another Context. Can be subclassed to modify behavior without changing the original Context."
(as per javadocs)..
Now, a question might arise ! How would one access the Context object inside of a class that
does not extend Activity ? So, it can be achieved by :
Passing Context as an object to other class: For a class that does not have an access to
any of the Context mentioned above. Context can be passed to such class through its
constructor.
Example:
And finally, to get Context anywhere in your application you can define a new class in your
application :
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
<application
android:name="com.example.app.MyContext "
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
.......
<activity
......
</activity>
To get Context anywhere in your application, i.e. in any class of your project, you can call the
function of this class, like this:
MyContext.getContext();
This function will return a Context that you can use to carry out your tasks.
So, coming to your question. I guess the last two methods can solve your problem i.e passing the
Context object to the class and define a new class that extends Application.