Skip to main content
Version: 11.11.0

Sending messages from/to Sender to/from Receiver on Android

This article will explain how to send data to an active receiver and how to respond on the receiver.

Send data to the receiver​

The Google Cast SDK has a global object that everyone can access. This global object is also being used by THEOplayer. The general idea is to retrieve the current active cast session and send a message on a specific namespace.

// Retrieve the current cast session
val castSession = CastContext.getSharedInstance(this).sessionManager.currentCastSession
// Send message on defined namespace channel
castSession?.sendMessage("namespace", "message")

Reference:

Receive data from the receiver​

The general idea is to retrieve the current active cast session and add an event listener on the specific namespace.

// Retrieve the current cast session
val castSession = CastContext.getSharedInstance(this).sessionManager.currentCastSession
// Create callback handler
val callback = Cast.MessageReceivedCallback { castDevice, namespace, message ->
// Do something with the message
}
// Add the message listener to the current cast session
castSession?.setMessageReceivedCallbacks("namespace", callback)

Reference:

Receive data on the receiver​

This example is for receiver version 2.

The general idea is to retrieve the receiver manager and add a message listener for the specific namespace. This needs to be done before a THEOplayer instance is created. THEOplayer will call the start method of the receiverManager on initialization.

// Retrieve the cast receiver manager
var castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
// Retrieve the message bus from the cast receiver manager
var messageBus = castReceiverManager.getCastMessageBus('namespace');
// Add message listener to the message bus
messageBus.onMessage = function (event) {
console.log(event);
};

Reference:

Send data from the receiver​

This example is for receiver version 2.

There are multiple possibilities to send data from the receiver:

  1. When a message is received on the receiver, you can answer the sender

  2. Broadcast to all connected senders

// 1.
messageBus.onMessage = function (event) {
messageBus.send(event.senderId, 'message');
};
// 2.
messageBus.broadcast('message');

Reference: