2

I try to use Firebase for push notifications for Android. But I faced very strange issue. All is OK when I send push in foreground. All is OK when I send push in background (I sending only data), until I come back to foreground and then back to background.

My FirebaseMessagingService is not called when I have my app goes to background in the second time. Also, please notice that I use Android Emulator. Code:

public class MyAndroidFirebaseMsgService extends FirebaseMessagingService {
    private static final String TAG = "MyAndroidFCMService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
    }
}

//... 

public class MyAndroidFirebaseInstanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyAndroidFCMIIDService";

    @Override
    public void onTokenRefresh() {
        //Get hold of the registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        //Log the token
        Log.d(TAG, "Refreshed token: " + refreshedToken);
    }
    private void sendRegistrationToServer(String token) {
        //Implement this method if you want to store the token on your server
    }
}

AndroidManifest.xml:

<service android:name=".MyAndroidFirebaseMsgService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".MyAndroidFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

Server:

curl -H "Content-type: application/json" -H "Authorization:key=<MYKEY>"  -X POST -d '{"to": "<MYTOKEN>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send

How can I solve it?

Grimthorr
  • 6,246
  • 5
  • 37
  • 51
konstantin_doncov
  • 2,228
  • 3
  • 29
  • 80

1 Answers1

0

This is working as intended, notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If your app is in the background or closed then a notification message is shown in the notification center, and any data from that message is passed to the intent that is launched as a result of the user tapping on the notification.

You can specify a click_action to indicate the intent that should be launched when the notification is tapped by the user. The main activity is used if no click_action is specified.

When the intent is launched you can use the

getIntent().getExtras(); to retrieve a Set that would include any data sent along with the notification message.

For more on notification message https://firebase.google.com/docs/cloud-messaging/android/receive#sample-receive

android_jain
  • 752
  • 7
  • 19