[ACCEPTED]-Is it always safe to cast Context to Activity within View-android

Accepted answer
Score: 57

As I know, It is not always safe because, the 4 context also can be passed from os to a 3 Service, BroadcastReceiver, etc. But, almost 2 of case, that is not a problem. just check 1 with this code

if(context instanceof Activity)

and feel free to use.

Score: 7

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;
}

0

Score: 3

Technically, Views can be created with any 4 Context (via the LayoutInflater)

So unless you are super 3 sure that your Views are only instantiated 2 by Activities, I wouldn't suggest this. Doing 1 this is not a clean idea.

Score: 2

While I can't think of such case, I think 1 it is not such a great idea for two reasons:

  1. Why would you want to do that, when do you explicitly need Activity?
  2. What if tomorrow this will be changed, and there will be other context for View?

More Related questions