I am working on a chat application where pictures are discussed.
When I receive a c2dm message, the payload contains the message and an md5 which identifies the picture this message is about. When a ChatActivity with a matching md5 is in foreground I want to only play a sound. When it is not, I want to add a notification to the notification bar.
This is the same behaviour as with whatsapp. How to implement this?
Have the
ChatActivityregister aBroadcastReceiverto receive the C2DM message, in addition to having your existing manifest-registerdBroadcastReceiverfor the C2DM message. Have theIntentFilterused by theChatActivityinregisterReceiver()use a positive value forsetPriority(), as the default is 0. UseregisterReceiver()inonResume()oronStart(), and useunregisterReceiver()inonPause()oronStop().The result is that when the C2DM message arrives, if your
ChatActivityis in the foreground, it will get the message first, due to the higher priority. It can do the check to see if the message is about its image. If it is,ChatActivity‘sBroadcastReceivercan callabortBroadcast(), to prevent your standard-priority manifest-registered receiver from getting the broadcast. Hence, if your manifest-registered receiver does get the broadcast, you know there was no relevantChatActivityin the foreground, and it can raise theNotification.Here is a sample app that demonstrates most of this. The broadcast is coming from the app itself, rather than C2DM, but the rest of the structure is pretty much the same.