Reputation: 31
hey i have an android application in which i monitor gmail server in a thread in background..this thread runs infinitely ...on getting a mail in the mailbox I have to make a toast..but i am not able to get the context of current activity(since there are multiple activities in the app)...how to get context of current running activity or may be application..getApplicationcontext gives null.
Upvotes: 3
Views: 24755
Reputation: 24484
In toasts and listeners and everywhere, if you need to get resources, You could use
Resources.getSystem().getString(android.R.string.cancel)
It has absolutely universal placement, but supports only system resources.
Upvotes: 3
Reputation: 11571
Use this or getApplicationContext() to get the current context. For example,
Context mContext=this;
or
Context mContext=getApplicationContext();
If the actvity is any child Acivity of some tabHost, then try getParent().getApplicationContext() also.
Upvotes: 2
Reputation: 40401
If you're running an Activity
or a Service
, both are Context
themselves, so calling this
suffice. On any callback method for a listener, this
will refer to the listener, not to the Activity
. You can refer to the Context
using any View
:
Context context = myView.getContext();
Upvotes: 10
Reputation: 7706
You can get the context of the Activity by calling on the Class name. For instance, if you Activity is called from inside MainActivity
you can get the context by typing:
Context context = this;
Upvotes: 0