Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

android - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...