I have a class that extends GCMBaseIntentService, when I get a message from gcm function:
@Override
protected void onMessage (Context context, Intent intent)
{
String message = intent.getExtras().GetString("alien");
generateNotification (context, message);
}
I wish that when a new message arrives the app recognize if the application is open and the user is using, or is a simple background service, and therefore I see a notification. I need to know if it is in the background or foreground, any suggestions ??
A pretty common approach to solving this problem is using an event bus to publish the message to the rest of your app to see if anyone is registered to handle it.
A good event bus for Android is the greenrobot EventBus https://github.com/greenrobot/EventBus
A code example of how to do it:
Create a class for your message
Add the
EventBus
to yourBroadcastReceiver
Then, in your Activity:
This way, if your activity is active, it can process the
MessageEvent
, if it is not active, you can display the notification as usual.To do that, you can use an in-process event bus. Have the service post an event to the bus. Have the UI subscribe to the bus for those events when the UI is in the foreground (e.g., register in
onResume()
, unregister inonPause()
). Have the UI process the events when the UI gets them. If the UI does not respond to the event, the service can then raise aNotification
.I have sample apps that demonstrate this for three popular event bus implementations for Android:
LocalBroadcastManager
: https://github.com/commonsguy/cw-omnibus/tree/master/EventBus/LocalBroadcastManagergreenrobot's EventBus: https://github.com/commonsguy/cw-omnibus/tree/master/EventBus/GreenRobot
Square's Otto: https://github.com/commonsguy/cw-omnibus/tree/master/EventBus/Otto
GCM runs completely at background and not in foreground.
You will use these two permission's which is to receive the message at background.
Please read this.
https://developer.android.com/google/gcm/client.html