Search code examples
androidchromecastgoogle-cast

Filtering Or Hiding Available ChromeCast Devices


I'm working on an app using Chromecast and I want to be able to filter the available devices or routes based on device name or description. So when a user clicks the MediaRouteButton only some of the available devices would show. The use case for my app happens in a place where many cast devices are available and I want to make sure the user doesn't accidentally select a device in another room. The user information in the app stores the room information that the user is based in and the chromecasts are being named in an intelligent way so that, ideally, only the chromecast device for a specific user's room would show up as available to them.

I have tried grabbing the MediaRouteDialogFactory and filtering devices at that level but have had no luck. There doesn't seem to be any mechanism that I can find to hide or remove routes.


Solution

  • To filter Chromecast devices from chooser dialog you can use onFilterRoute:

    public boolean onFilterRoute (MediaRouter.RouteInfo route)
    Returns true if the route should be included in the list.

    The default implementation returns true for enabled non-default routes that match the selector. Subclasses can override this method to filter routes differently.

    You need to create a CustomMediaRouteChooserDialog:

    public class CustomMediaRouteChooserDialog extends MediaRouteChooserDialog {
        public CustomMediaRouteChooserDialog(Context context) {
            super(context);
        }
    
        public CustomMediaRouteChooserDialog(Context context, int theme) {
            super(context, theme);
        }
    
        @Override
        public boolean onFilterRoute(MediaRouter.RouteInfo route) {
            // Apply your logic here.
            // Return false to hide the device, true otherwise
    
            if (TextUtils.equals(route.getName(), "Chromecast-hidden"))
                return false;
            else
                return true;
        }
    }
    

    Then create a CustomMediaRouteChooserDialogFragment:

    public class CustomMediaRouteChooserDialogFragment extends MediaRouteChooserDialogFragment {
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            CustomMediaRouteChooserDialog dialog = new CustomMediaRouteChooserDialog(getActivity());
            dialog.setRouteSelector(getRouteSelector());
            return dialog;
        }
    }
    

    Then create a CustomMediaRouteDialogFactory:

    public class CustomMediaRouteDialogFactory extends MediaRouteDialogFactory {
    
        @Override
        public MediaRouteChooserDialogFragment onCreateChooserDialogFragment() {
            return new CustomMediaRouteChooserDialogFragment();
        }
    }
    

    Then after create your MediaRouteActionProvider call setDialogFactory:

    mediaRouteActionProvider.setDialogFactory(new CustomMediaRouteDialogFactory());