Real-Time Android Messaging With Pusher

Pusher is a hosted API for real-time JSON messaging in web and mobile applications via WebSockets.

Examples Pusher applications:

I recently used Pusher at Breezy to notify user’s printers when documents sent from their mobile devices are ready to be printed. It’s very fast (real-time!) and powerful stuff, and I immediately started thinking about ways to implement it in Android applications.

Surprisingly, nobody had built a full-featured Java / Android client for Pusher, so I decided to build one.

Pusher is event-driven, so the first thing to do is create an event listener:
[java]
PusherListener eventListener = new PusherListener() {
@Override
public void onConnect(String socketId) {
System.out.println("Pusher connected. Socket Id is: " + socketId);
}

@Override
public void onMessage(String message) {
System.out.println("Received message from Pusher: " + message);
}

@Override
public void onDisconnect() {
System.out.println("Pusher disconnected.");
}
};
[/java]

Next, create an instance of the Pusher class and pass it the API key you were assigned while signing up for Pusher. Then set the event listener from the previous step and connect:
[java]
Pusher pusher = new Pusher(YOUR_API_KEY);
pusher.setPusherListener(eventListener);
pusher.connect();
[/java]

Pusher’s communication happens over public, private or presence Channels, and you can bind to or trigger events on any of these channel types:
[java]
// Public Channel
channel = pusher.subscribe(PUSHER_CHANNEL);
// Private Channel
channel = pusher.subscribe(PUSHER_CHANNEL, AUTH_TOKEN);
// Presence Channel
channel = pusher.subscribe(PUSHER_CHANNEL, AUTH_TOKEN, USER_ID);
// Trigger an event
channel.send("trigger-event", new JSONObject());
// Bind to the "price-updated" event with a ChannelListener
channel.bind("price-updated", new ChannelListener() {
@Override
public void onMessage(String message) {
System.out.println("Received bound channel message: " + message);
}
});
[/java]

The Java / Android Pusher library can be found on GitHub here.

Please let me know if you have any feedback or questions.

Comments

One response to “Real-Time Android Messaging With Pusher”

Leave a Reply

Your email address will not be published. Required fields are marked *