Sending media to Chromecast has never been easier (Exoplayer cast extension)

Mateusz Kaflowski
AndroidPub
Published in
2 min readMar 22, 2018

--

If you have been implemented Chromecast handling in your app you probably noticed that it is a little bit complicated and tricky. Some thing just doesn’t want to work. Thanks to new ExoPlayer extension it is a lot of easier now.

Import libraries.

You need to import libraries first. Just add them in gradle file:

compile 'com.google.android.exoplayer:exoplayer:2.7.0'
compile 'com.google.android.exoplayer:extension-cast:2.7.0'

If you are using some com.google.android.gms libraries (Firebase for example) you can see some inconsistency warnings. You can fix that by adding:

compile 'com.google.android.gms:play-services-cast-framework:<YOUR_VERSION>'

Declare an OptionProvider.

Declare an OptionProvider class in the app’s AndroidManifest.xml in. This will allow specifying the receiver app.

Add UI elements.

First of all you need to add some user interface elements for connecting with your Chromecast receiver. The easiest way is to add MediaRouteButton just like in official doc.

As option in toolbar:

As view:

I have noticed that MediaRouteButton as a view doesn’t show up on Chromecast available which works well in menu version so I do something like that:

It is also good to initialize CastContext in onCreate() to avoid some strange glitches like missing notification:

CastContext castContext = CastContext.getSharedInstance(this);

Add Proguard rules:

# Accessed via menu.xml
-keep class android.support.v7.app.MediaRouteActionProvider {
*;
}

Declare media source and connect to Chromecast receiver.

Create media queue:

Create CastPlayer object and handle media queue:

And that’s it! Don’t forget to release CastPlayer with realease(). You can control player with built-in methods like seek(), pause() and so on. For selecting stream from queue use: seekTo(windowIndex, msec).

Can I make it easier and connect it with player on sender phone?

Yes and yes!

I have made player library to make playing audio and video on your phone and integrating with Chromecast even easier. I will write about it soon!

--

--