The sender framework refers to the Cast class library binary and associatedresources present at runtime on the sender. The sender app or Cast apprefers to an app also running on the sender. The Web Receiver apprefers to the HTML application running on the Cast-enabled device.
For a comprehensive list of all classes, methods and events in the Google CastAndroid SDK, see the Google Cast Sender API Reference forAndroid.The following sections cover the steps for you to add Cast to your Android app.
Set your app's theme based on the minimum Android SDK version. For example, ifyou are not implementing your own theme, you should use a variant ofTheme.AppCompat when targeting a minimum Android SDK version that ispre-Lollipop.
Your app must implement theOptionsProviderinterface to supply options needed to initialize theCastContextsingleton. OptionsProvider provides an instance ofCastOptionswhich contains options that affect the behavior of the framework. The mostimportant of these is the Web Receiver application ID, which is used to filterdiscovery results and to launch the Web Receiver app when a Cast session isstarted.
Introductory Overlay:The framework provides a custom View,IntroductoryOverlay,that is shown to the user to call attention to the Cast button thefirst time a receiver is available. The Sender app cancustomize the text and the position of the titletext.
Cast Button:The Cast button is visible regardless of the availability of Cast devices.When the user first clicks on the Cast button, a Cast dialog is displayedwhich lists the discovered devices. When the user clicks on the Cast buttonwhile the device is connected, it displays the current media metadata (such astitle, name of the recording studio and a thumbnail image) or allows the userto disconnect from the Cast device. The "Cast button" is sometimes referred toas the "Cast icon".
Mini Controller:When the user is casting content and has navigated away from the currentcontent page or expanded controller to another screen in the sender app, themini controller is displayed at the bottom of the screen to allow the user tosee the currently casting media metadata and to control the playback.
Expanded Controller:When the user is casting content, if they click on the media notificationor mini controller, the expanded controller launches, which displays thecurrently playing media metadata and provides several buttons to controlthe media playback.
Notification:Android only. When the user is casting content and navigates away from thesender app, a media notification is displayed that shows the currently castingmedia metadata and playback controls.
Lock Screen:Android only. When the user is casting content and navigates (or the devicetimes out) to the lock screen, a media lock screen control is displayed thatshows the currently casting media metadata and playback controls.
The AndroidMediaRouterAPIs are designed to enable media display and playback on secondary devices.Android apps that use the MediaRouter API should include a Cast button as partof their user interface, to allow users to select a media route to play media ona secondary device such as a Cast device.
The framework makes adding aMediaRouteButtonas aCast buttonvery easy. You should first add a menu item or a MediaRouteButton in the xmlfile that defines your menu, and useCastButtonFactoryto wire it up with the framework.
Device discovery is completely managed by theCastContext.When initializing the CastContext, the sender app specifies the Web Receiverapplication ID, and can optionally request namespace filtering by settingsupportedNamespaces inCastOptions.CastContext holds a reference to the MediaRouter internally, and will startthe discovery process under the following conditions:
The Cast SDK introduces the concept of a Cast session, theestablishment of which combines the steps of connecting to a device, launching (or joining) a WebReceiver app, connecting to that app, and initializing a media control channel. See the Web ReceiverApplication life cycle guidefor more information about Cast sessions and the Web Receiver life cycle.
Sessions are managed by the classSessionManager,which your app can access viaCastContext.getSessionManager().Individual sessions are represented by subclasses of the classSession.For example,CastSessionrepresents sessions with Cast devices. Your app can access the currently activeCast session viaSessionManager.getCurrentCastSession().
Your app can use theSessionManagerListenerclass to monitor session events, such as creation, suspension, resumption, andtermination. The framework automatically attempts to resume from anabnormal/abrupt termination while a session was active.
To better understand Cast starting errors, apps can useCastContext#getCastReasonCodeForCastStatusCode(int)to convert the session starting error toCastReasonCodes.Please note that some session starting errors (e.g. CastReasonCodes#CAST_CANCELLED)are intended behavior and should not be logged as an error.
Preserving session state is the basis of stream transfer, whereusers can move existing audio and video streams across devices using voice commands, Google HomeApp, or smart displays. Media stops playing on one device (the source) and continues on another (thedestination). Any Cast device with the latest firmware can serve as sources or destinations in astream transfer.
To get the new destination device during a stream transfer or expansion,register aCast.Listenerusing theCastSession#addCastListener.Then callCastSession#getCastDevice()during the onDeviceNameChanged callback.
The Cast framework deprecates theRemoteMediaPlayerclass from Cast 2.x in favor of a new classRemoteMediaClient,which provides the same functionality in a set of more convenient APIs, andavoids having to pass in a GoogleApiClient.
When your app establishes aCastSessionwith a Web Receiver app that supports the media namespace, an instance ofRemoteMediaClient will automatically be created by the framework; your app canaccess it by calling getRemoteMediaClient() method on the CastSessioninstance.
It is expected that the instance of RemoteMediaClient may be shared bymultiple parts of your app, and indeed some internal components of theframework, such as the persistent mini controllers andthe notification service.To that end, this instance supports registration of multiple instances ofRemoteMediaClient.Listener.
Your app can load a media item, as shown in the following code. First useMediaInfo.Builder with the media's metadata to build aMediaInfoinstance. Get theRemoteMediaClientfrom the current CastSession, then load the MediaInfo into thatRemoteMediaClient. Use RemoteMediaClient to play, pause, and otherwisecontrol a media player app running on the Web Receiver.
To check what video format your media is, usegetVideoInfo()in MediaStatus to get the current instance ofVideoInfo.This instance contains the type of HDR TV format and the display heightand width in pixels. Variants of 4K format are indicated by constantsHDR_TYPE_*.
When a user is casting, other Android devices on the same network will geta notification to also let them control the playback. Anyone whose devicereceives such notifications can turn them off for that device in the Settingsapp at Google > Google Cast > Show remote control notifications.(The notifications include a shortcut to the Settings app.) For more detail, seeCast remote control notifications.
According to the Cast DesignChecklist,a sender app should provide a persistent control known as the minicontrollerthat should appear when the user navigates away from the current content page toanother part of the sender app. The mini controller provides a visible reminderto the user of the current Cast session. By tapping on the mini controller, theuser can return to the Cast full-screen expanded controller view.
The framework automatically manages the volume for the sender app. The frameworkautomatically synchronizes the sender and Web Receiver apps so that the senderUI always reports the volume specified by the Web Receiver.
To use the physical volume keys to control the Web Receiver device volume onAndroid devices older than Jelly Bean, the sender app should overridedispatchKeyEventin their Activities, and callCastContext.onDispatchVolumeKeyEventBeforeJellyBean():
On Android only, the Google Cast Design Checklist requires a sender app toimplement media controls in anotificationand in the lockscreen,where the sender is casting but the sender app does not have focus. Theframework providesMediaNotificationServiceandMediaIntentReceiverto help the sender app build media controls in a notification and in the lockscreen.
Your app can configure notification and media control from lock screen throughNotificationOptions.Your app can configure what control buttons to show in the notification, andwhich Activity to open when the notification is tapped by the user. If actionsare not explicitly provided, the default values,MediaIntentReceiver.ACTION_TOGGLE_PLAYBACK andMediaIntentReceiver.ACTION_STOP_CASTING will be used.
Showing media controls from notification and lock screen are turned on bydefault, and can disabled by callingsetNotificationOptionswith null inCastMediaOptions.Builder.Currently, the lock screen feature is turned on as long as notification isturned on.
When your sender app is playing a video or audio live stream, the SDKautomatically displays a play/stop button in place of the play/pause buttonon the notification control but not the lock screen control.
It is very important for sender apps to handle all error callbacks and decidethe best response for each stage of the Cast life cycle. The app can displayerror dialogs to the user or it can decide to tear down the connection to theWeb Receiver.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
c80f0f1006