问题
I'm building an action which utilizes Google Cloud Messaging for receiving push notifications.
This involves a couple notable components, namely:
- A
WakefulBroadcastReceiver
to receive the message from GCM. - An
IntentService
to be notified when a GCM event is received.
As I'm sure is the case for many applications, I'd like to take a different approach for when the application has an activity in the foreground vs. when the application does not have an application in the foreground.
I'd like to post a notification to the notification drawer if the application is not active, and simply forward the event onto the foreground activity if the application is active.
Is there a design pattern for this? How should I go about determining if the app is in the foreground vs. the background?
回答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.
回答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...
来源:https://stackoverflow.com/questions/22001844/design-pattern-for-alternate-action-if-app-in-foreground