Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always safe to cast Context to Activity within View

Tags:

android

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?

like image 236
Cheok Yan Cheng Avatar asked Sep 06 '25 18:09

Cheok Yan Cheng


2 Answers

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.

like image 136
lulumeya Avatar answered Sep 10 '25 06:09

lulumeya


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;
}
like image 25
Hexise Avatar answered Sep 10 '25 05:09

Hexise