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:
- Updating a website or mobile application with sports scores or stock prices in real-time
- Sending real-time messages to Arduino devices from a web or mobile application
- Building a real-time donation thermometer on a website
- Tracking multi-player game moves… in real-time
- You get the idea…
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:
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."); } };
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:
Pusher pusher = new Pusher(YOUR_API_KEY); pusher.setPusherListener(eventListener); pusher.connect();
Pusher’s communication happens over public, private or presence Channels, and you can bind to or trigger events on any of these channel types:
// 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); } });
The Java / Android Pusher library can be found on GitHub here.
Please let me know if you have any feedback or questions.
About this entry
You’re currently reading “ Real-Time Android Messaging With Pusher ,” an entry on Public Static Droid Main
- Published:
- 1.15.12 / 6pm
- Category:
- Uncategorized
No comments
Jump to comment form | comments rss [?] | trackback uri [?]