Gimali
Gimali

Reputation: 787

GcmListenerService onMessageReceived called only when app is in foreground

I have following manifest -

<service
    android:name=".RegistrationIntentService"
    android:exported="false" />

<service
    android:name=".TestGcmListenerService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.example.test" />
    </intent-filter>
</service>

<service
    android:name=".RegistrationIDListenerService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.android.gms.iid.InstanceID" />
    </intent-filter>
</service>

<receiver
    android:name="com.google.android.gms.gcm.GcmReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />

        <category android:name="com.example.test" />
    </intent-filter>
</receiver>

And following onMessageReceived method -

@Override
    public void onMessageReceived(String from, Bundle data) {
        ObjectMapper objectMapper = new ObjectMapper();
        Message message;
        try {
            message = objectMapper.readValue(String.valueOf(data.get("message")), Message.class);
            MessageNotification.notify(this, message, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

What happens is, onMessageReceived gets called only when app is in foreground. Otherwise it doesn't get called and notification is not shown. When I open the app all notifications are shown at once.

Doesn't GcmListenereService wake up device if locked and do the work ? How to solve this ?

Upvotes: 1

Views: 685

Answers (1)

AL.
AL.

Reputation: 37808

Googled around and managed to find this thread on github which is pretty much the same as your concern, where onMessageReceived() is only called when app is on foreground. The reason was because only Notification Messages are sent. As per the description included in the thread:

Notification Messages - these are intended to generate a notification with no intermediate processing by the application. They only hit onMessageReceived if the app is running.

Data Messages - these are intended to silently pass data to the app's messaging service. They hit onMessageReceived even if the app is in the background. The service may then choose to generate a notification using the normal system notification APIs, or it may choose to handle the message silently.

I think you are sending Notification Messages while expecting the behavior for Data Messages to kick in.

Here's also the SO post of Shiprack mentioned in the github thread. Hope this helps. Good luck.

Upvotes: 1

Related Questions