1

I am developping an instant messaging application that uses Google Cloud Messaging. I send a notification when a user receive a message from a contact. Everything works properly. I set up the GCMBroadcastReceiver and the GCMMessageHandler. The problem is : the notification is always displaying even if the user is currently chatting with his contact. How can I know the application state in the GCMMessageHandler to not display the notification ?

Here is the GCMBroadcastReceiver :

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    // Explicitly specify that GcmMessageHandler will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmMessageHandler.class.getName());

    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}

}

Here is the GCMMessageHandler :

protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    mes = extras.getString("message");

    if(IM_NOT_IN_THE_CHAT_ACTIVITY)
    {
        showNotification(mes);
    }

What I'm struggling to get is that flag : IM_NOT_IN_THE_CHAT_ACTIVITY.

How can I know this in the IntentService ?

Jean Col
  • 522
  • 5
  • 16
  • See the 3rd answer down on this question: http://stackoverflow.com/questions/3873659/android-how-can-i-get-the-current-foreground-activity-from-a-service It's talking about a service but you can still use the checking portion of the code. I've used it in a chat app and it works perfectly. – Peter Nov 20 '15 at 12:08

1 Answers1

0

Doing this would do the trick I guess :

    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
    String activity_name = taskInfo.get(0).topActivity.getClassName();


    if(activity_name != ACTIVITY_NAME)
        showNotification(mes);
Jean Col
  • 522
  • 5
  • 16