0

How do I send a push a notification, even when the app is in the background? I have an android app that recieves push notifications from a server and it does not send when the app is in the background. it only sends when the app is in the background.

  • 1
    Possible duplicate of [How to handle the fire base notification when app is in foreground](https://stackoverflow.com/questions/38451235/how-to-handle-the-fire-base-notification-when-app-is-in-foreground) – Zankrut Parmar Oct 30 '18 at 05:03

1 Answers1

0

You need to add this in your manifest file:

    <service
        android:name=".name_of_your_firebase_instace_service"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service
        android:name=".nname_of_your_firebase_messaging_service
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

This is the class for refreshing token(instance service)

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();




    // sending reg id to your server
    sendRegistrationToServer(refreshedToken);

    Log.d("NewToken",refreshedToken);

}

private void sendRegistrationToServer(final String token) {
    // sending gcm token to server
    Log.e(TAG, "sendRegistrationToServer: " + token);
}

 }

Mmessage service where you will receive your message/notification

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

private NotificationUtils notificationUtils;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.


    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
        //you can send your own custom notification here if you are sending notification in data tag or if you are sending notification with "notification tag" it will handle it automatically


    }
}
}

Note: do not forget to add your google-service.json file in app folder of your project

piet.t
  • 11,718
  • 21
  • 43
  • 52
sourabh kaushik
  • 523
  • 4
  • 20