1

I'm building an app with notification. The app sends notification when something comes from the server. Now I want to mute the sounds for notifications when the current app is active.

So I need to know when my app is active and what activity is active now.

I found this answer on stackoverflow:

Determining the current foreground application from a background task or service

But it is not the shortcut for me, because it requires me to 1. Get the list of running apps, 2. Find the app that active right now 3. Find the activity the active now 4. Check if the activity is what i need.

But how can i simply check when my app's activity is active?

Hope I succeeded to explain myself well.

Thanks

Community
  • 1
  • 1
Ilya Libin
  • 1,576
  • 2
  • 17
  • 39
  • 2
    commonsware has a very good article about this : http://commonsware.com/blog/2010/08/11/activity-notification-ordered-broadcast.html – njzk2 May 12 '14 at 17:31
  • http://stackoverflow.com/questions/4414171/how-to-detect-when-an-android-app-goes-to-the-background-and-come-back-to-the-fo?lq=1 – user2125722 May 12 '14 at 17:50

1 Answers1

0

I'm building an app with notification. The app sends notification when something comes from the server. Now I want to mute the sounds for notifications when the current app is active.

IMHO, that's not a great design choice. If your UI is in the foreground, you should not have a Notification at all, but instead update your UI to reflect whatever event occurred in the background.

So I need to know when my app is active and what activity is active now.

In a comment, njzk2 pointed to an older blog post of mine on the activity-or-notification pattern. While the pattern is still valid, using ordered broadcasts is not a great choice. You are better served using an in-process message bus (LocalBroadcastManager, Square's Otto, greenrobot's EventBus) instead.

But the basic approach is the same regardless of communications channel: raise an event to tell your UI layer (activities and fragments) that the event occurred. Activities and/or fragments register for those events when they are in the foreground (e.g., onResume()) and unregister for those events when they are not (e.g., onPause()). If nothing picks up the event, have a "backstop" handler that detects this condition and performs a fallback action, like raising the Notification.

I have three sample apps that demonstrate this using:

If you decide that you do indeed want to force the user to have to deal with your Notification even though your UI is in foreground, and you just want a differently-configured Notification, you will need to track for yourself which activity is in the foreground, again via onResume() and onPause().

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491