May I know, is it safe for me to always cast Context
to Activity
within a View
?
View {
Activity activity = (Activity)this.getContext();
}
So far, it works fine all the moment. I was wondering, is there any edge cases that the above code will fail?
As I know, It is not always safe because, the context also can be passed from os to a Service, BroadcastReceiver, etc. But, almost of case, that is not a problem. just check with this code
if(context instanceof Activity)
and feel free to use.
I think you can use following snippet:
/**
* Get activity instance from desired context.
*/
public static Activity getActivity(Context context) {
if (context == null) return null;
if (context instanceof Activity) return (Activity) context;
if (context instanceof ContextWrapper) return getActivity(((ContextWrapper)context).getBaseContext());
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With