getting context in java android
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 c开发者_运维知识库urrent running activity or may be application..getApplicationcontext gives null.
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();
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.
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.
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;
精彩评论