Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android GCM: different way of handling push depending on whether the app is visible or not

I've got a couple of activities and an intent service which handles GCM incoming messages.

Right now for every push, I'm sending a Notification, and after the user clicks it, he is redirected to appropriate screen.

I would like to alter this behavior that if the app is visible (any activity is in the foreground), instead of the notification a dialog message is shown (with appropriate action).

Any idea how to implement it?

I have 2 ideas but none of them is perfect:

  • Keep track of every activity in the application, if the activity is visible, don't show notification, but sent an intent to the activity (not nice solution)
  • register/unregister the second broadcast receiver in each activity's onResume/onPause, "catch" the incoming GCM broadcast (I'm not sure if it is possible).

Any other solutions?

like image 739
kmalmur Avatar asked Apr 07 '14 10:04

kmalmur


1 Answers

A possible solution (idea 1):

To detect whether your app is running back- or foreground, you can simply set a boolean in onPause/onResume:

@Override
protected void onResume() {
  super.onResume();
  runningOnBackground = false;
}

@Override
protected void onPause() {
  super.onPause();
  runningOnBackground = true;
}

When you start a new intent from an notification this method gets called: (if you are using singleTop), with the boolean you can determine what to do in the onNewIntent method.

@Override
protected void onNewIntent (Intent intent){
  if(runningOnBackground){
    //do this
  }
  else{
    //do that
  }
}

Hope it helps!

like image 184
Daan Oerlemans Avatar answered Oct 14 '22 22:10

Daan Oerlemans