Skip to content Skip to sidebar Skip to footer

Design Pattern For Alternate Action If App In Foreground?

I'm building an action which utilizes Google Cloud Messaging for receiving push notifications. This involves a couple notable components, namely: A WakefulBroadcastReceiver to r

Solution 1:

You can follow an approach as outlined in this blog post where you create a BroadcastReceiver in your Activity with a positive priority (i.e., higher than the default of 0) which intercepts a specific action and then calls abortBroadcast - this handles the app open case. You then also register a BroadcastReceiver in your Manifest which handles the same action but at the default priority - this is the fallback if the app is not open and it creates the system notification.

You then use sendOrderedBroadcast() to send your broadcast to all registered receivers in priority order. If the activity is open, the first will handle it. Otherwise, it will default to the other one and create a notification.

Solution 2:

The way I suggest doing it is as following.

Have all the logic regarding GCM in a Service (I've never used IntentService, so I don't know about it's guts, but I see it inherits from Service).

In your activity, you probably have a way of starting the service (perhaps the user activates through a button), nothing new here.

Here comes the fun part. In your activity you handle onPause() and onResume(). In onResume() you bind to the service. With the binding mechanism you can get a pointer to your service and let it know that you're there "hey service, I'm an activity and I'm here... please store a pointer to myself somewhere", and the service stores a pointer to the activity (let's call it mActivity). In your onPause() you notify the service that you're leaving, so the service sets mActivity = null, and then you unbind from the service.

With this mechanism, every time the Service receives a push notification, it tests the mActivity variable to see if there's a bound Activity. With a pointer to your Activity you can invoke any of it's methods, forward information...

Post a Comment for "Design Pattern For Alternate Action If App In Foreground?"