Search code examples
androidbroadcastreceiverandroid-c2dmgoogle-cloud-messaging

Android: determine wether broadcast was received


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?


Solution

  • Have the ChatActivity register a BroadcastReceiver to receive the C2DM message, in addition to having your existing manifest-registerd BroadcastReceiver for the C2DM message. Have the IntentFilter used by the ChatActivity in registerReceiver() use a positive value for setPriority(), as the default is 0. Use registerReceiver() in onResume() or onStart(), and use unregisterReceiver() in onPause() or onStop().

    The result is that when the C2DM message arrives, if your ChatActivity is 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's BroadcastReceiver can call abortBroadcast(), 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 relevant ChatActivity in the foreground, and it can raise the Notification.

    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.