« « Shapeoko 2 Review | Simple Fix For Arduino Motor Shield Problem » »

How To Auto Connect To A Chromecast Device In Android

Feb 18, 2014 by     No Comments    Posted under: Android, Chromecast, Tutorials

ChromecastHere’s a handy feature that’s not well documented yet. Let’s say you’re making an Android app that needs to connect to a Chromecast device as soon as the app launches. The existing examples make the user tap on a menu icon in the action bar, then choose a Chromecast device, then connect. That’s great, but what if you don’t want to make the user go through all that work?

You’ll have to make some assumptions about how many Chromecast devices will be available at any given time or save the user’s preferred device somewhere, but automatically connecting to the first available device is easy. Set up your Chromecast connection according to Google’s basic instructions, then override the method “onRouteAdded” in your MediaRouter.Callback:

private class MediaRouterCallback extends MediaRouter.Callback {

    @Override

    public void onRouteAdded(MediaRouter router, RouteInfo route)

    {

        //attempt to autoconnect to chromecast

        if(mSelectedDevice == null

            && route.supportsControlCategory(CastMediaControlIntent.categoryForCast(MyActivity.this.APP_ID)))

        {

            MyActivity.this.onRouteSelected(route);

        }

    }

    @Override

    public void onRouteSelected(MediaRouter router, RouteInfo route) {

        Log.d(TAG, "onRouteSelected: " + route);

        MyActivity.this.onRouteSelected(route);

    }

    @Override

    public void onRouteUnselected(MediaRouter router, RouteInfo route) {

        Log.d(TAG, "onRouteUnselected: " + route);

        MyActivity.this.onRouteUnselected(route);

    }

}

This will automatically connect to the Chromecast, but you’ll notice that if you click on the MediaRouter icon in the action bar, it doesn’t know that the Chromecast is connected. To update the action bar menu (if you are still using it), change your onRouteSelected method in the Activity to set the selected route:


private void onRouteSelected(RouteInfo route) {

    Log.d(TAG, "onRouteSelected: " + route.getName());

    mMediaRouter.selectRoute(route);

    CastDevice device = CastDevice.getFromBundle(route.getExtras());

    setSelectedDevice(device);

}

If you’ve saved the user’s preferred Chromecast device, you can add a check for that device name or id before you auto connect just to be safe. Hope that helps!

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>