I created an custom view and there require Activity reference to perform some Handler related operation. I have idea about getContext() is a way to get Context but is there any way to get Activity reference for same?

- 5,753
- 72
- 57
- 129

- 11,056
- 14
- 90
- 197
-
getContext is the correct way, since you are using you Actvity's context to inflate the View – Blackbelt Oct 25 '13 at 08:55
-
do you want to use getActivity() in a class that inherits from Activity class? – Himanshu Joshi Oct 25 '13 at 09:00
-
See my answer in stackoverflow.com/a/51077569/787399 – Abhinav Saxena Jun 28 '18 at 07:59
4 Answers
It should be fine to just cast the context to Activity:
MyActivity myActivity = (MyActivity) getContext();

- 1,359
- 1
- 13
- 18
-
1
-
1Please observe that getContext() may not return the host activity on some scenarios, like appwidgets or when you inflate a view without add it on the container, for some reason. – Renascienza Dec 28 '14 at 16:59
-
6
-
1True, thanks for the hint. Be carefull if you are outside of "ordinary" application context. – Jan Jan 01 '15 at 13:40
-
Casting getContext() to Activity (e.g. (Activity)getContext();) may not always return an Activity object if your View is not called from an Activity context.
So for that,
public Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
return null;
}
"while" is used to bubble up trough all the base context, till the activity is found, or exit the loop when the root context is found. Cause the root context will have a null baseContext, leading to the end of the loop.

- 2,034
- 26
- 22
-
This is the best answer and exactly what I came here for. Thank you it saved me a lot of time. – domenukk Aug 17 '16 at 13:21
-
Thanks, I just replaced ((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() { with getActivity().runOnUiThread( (new Thread(new Runnable() { and it works... – Christian Mar 08 '17 at 20:49
Pass context in the Constructor of View class like this
View Class
public class DrawView extends View {
Context actContext;
public DrawView(Context context) {
super(context);
actContext=context;
}
}
and in Your activity class
DrawView drawView=new DrawView(this);

- 6,907
- 2
- 24
- 35
-
Usually I do like that, works fine. Sometimes (in some situations) extra checks will be needed to avoid crash. – Andrew Feb 27 '15 at 22:30
You can get your activity reference by sending the context of your activity in the constructor of your handler when defining its objects and the constructor defination in the handler class is defined below:
private Context mContext;
public MyHandler(Context context) {
mContext=context;
}
and in yor main activity class you can make its object as follows:
MyHandler ca=new MyHandler(MainActivity.this);