The Mobile Backend provides a Pub/Sub messaging mechanism in
CloudBackendMessaging
(subclass of the
CloudBackendAsync
). Pub/Sub messaging is a software architectural pattern to describe a N:N message broadcasting between Publishers (message senders) and Subscribers (message receivers). The Mobile Backend relies on
Google Cloud Messaging
to push messages to Android devices and
Apple Push Notification Service
to push to iOS devices.
Subscribing to Cloud messages
The mobile backend enables devices to subscribe to topics on the backend. A topic is represented as a unique
String
. To subscribe to messages on a topic you first need to define a handler using
CloudCallbackHandler
:
CloudCallbackHandler<List<CloudEntity>> handler =
new CloudCallbackHandler<List<CloudEntity>>() {
@Override
public void onComplete(List<CloudEntity> messages) {
/* message processing logic */
}
};
You can also override the
onError()
for error handling logic.
To subscribe the handler to a topic, create a
CloudBackendMessaging
instance (passing your
Activity
or any
Context
instance) and call
subscribeToCloudMessage()
, passing a topic identifier (the
String
that uniquely represents the topic, e.g. "dogs" in the example) and the handler:
CloudBackendMessaging cloudBackendMessaging = new CloudBackendMessaging(activity);
cloudBackendMessaging.subscribeToCloudMessage("dogs", handler);
Sending a Cloud message
To send a message:
-
Create the message using
createCloudMessage()
: pass thetopicId
in theCloudBackendMessaging
instance. -
In the returned
CloudEntity
that represents the message, invokeput()
to add key-value pairs to the message. -
Use
sendCloudMessage()
to send the message to the subscribers.
The snippet below shows how to do all this:
CloudEntity ce = cloudBackendMessaging.createCloudMessage("dogs");
ce.put("dog-name", "Fido");
ce.put("dog-age", "5 days");
ce.put("message", "I have a new puppy!");
cloudBackendMessaging.sendCloudMessage(ce);
The received messages are passed to the handler’s
onComplete()
method as a
CloudEntity
List. You can write code to update UI components with the messages. In this way, developers can implement the logic behind a real-time chat application with about 10 lines of code.
Receiving offline messages
Call
subscribeToCloudMessage()
method to start receiving messages sent after the subscription call. However developers may want to receive older messages sent to a topic before the subscription was added. To do this, you can specify a third argument on the method call:
cloudBackendMessaging.subscribeToCloudMessage("dog", handler, 50);
As shown, the client will receive up to 50 messages sent in the past. This feature is useful for receiving messages missed due to network connectivity or inactivity of the client app.
The pub/sub messaging feature is implemented by using a
Continuous Query
. It creates a special entity
Kind
called
_CloudMessages
on Datastore to store the messages. When insertions with that kind and a specified topicId are made, the
CloudBackendMessaging
class receives the inserted message via a continuous query. Thus, all the messages are persisted on Datastore and can be retrieved later, even if the client app loses network connection.
In the [Guestbook sample] (https://github.com/GoogleCloudPlatform/solutions-mobile-backend-starter-android-client), the
CloudBackendFragment
class will automatically subscribe you to messages of broadcast ID
_broadcast
if the Fragment is added to your Activity.
Broadcast messages to activities
The Cloud Backend API can also broadcast messages. The
CloudBackendActivity
class provides a broadcasting implementation based on pub/sub messaging. The two sample classes,
GuestbookActivity
class and
SocialTalkActivity
class are good examples of how to use this feature.
You must subclass
CloudBackendActivity
:
public class GuestbookActivity extends CloudBackendActivity {
...
}
CloudBackendFragment
is a Fragment to be used as the basis of one of your Android screen's UI. Adding this Fragment to any Activity automatically performs basic subscriptions and registers listeners for you. The Fragment follows a standard Listener pattern of interaction with the Activity: your Activity must implement the Listener within the Fragment.
The
CloudBackendFragment
class has the following method within its Listener for message broadcasting:
onBroadcastMessageReceived()
. The
GuestbookActivity
implements the method to receive broadcast messages and show them to the user as
Toasts
:
@Override
public void onBroadcastMessageReceived(List<CloudEntity> l) {
for (CloudEntity e : l) {
String message = (String) e.get("message");
int duration = Integer.parseInt((String) e.get("duration"));
Toast.makeText(this, message, duration).show();
}
}
The snippet above retrieves two properties,
message
and
duration
, from the message to show a
Toast
with the message for the duration. You can also send messages with durations via the
Send Cloud Message
section of the
Mobile Backend Settings
page.
Broadcasting is implemented as a Cloud Message with a
topicId
_broadcast
.
To send a broadcast message, create a new message and then use the backend’s
insert()
method to send it:
CloudEntity cd = new CloudEntity("Guestbook");
cd.put("message", "my broadcast message");
ce.put("duration", "5");
cloudBackend.insert(ce, handler);
An example of this in usage can be found in the
GuestbookActivity
class.