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:
- https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus
- https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus#onMessage
- https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus.Event
Send data from the receiver
This example is for receiver version 2.
There are multiple possibilities to send data from the receiver:
-
When a message is received on the receiver, you can answer the sender
-
Broadcast to all connected senders
// 1.
messageBus.onMessage = function (event) {
messageBus.send(event.senderId, 'message');
};
// 2.
messageBus.broadcast('message');
Reference:
- https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus#broadcast
- https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus#send