Solution 1:

I just pulled that source code from the MediaRouter in the official support library and so far it works fine:

private Activity getActivity() {
    Context context = getContext();
    while (context instanceof ContextWrapper) {
        if (context instanceof Activity) {
            return (Activity)context;
        }
        context = ((ContextWrapper)context).getBaseContext();
    }
    return null;
}

Solution 2:

following methods may help you

  1. Activity host = (Activity) view.getContext(); and
  2. view.isFocused()