简体   繁体   中英

Can't create new notification while Firebase service runs in background

I used Firebase notifications, and made a class that extends FirebaseMessagingService . I made in this class a method that gets the message body and then shows a notification according to the payload.

My problem is, that this notification only works if my App is running, but when it's off, I get the default notification of Firebase, and not the customized one that I created.

My service class is:

public class FirebaseNotifications extends FirebaseMessagingService {

String lastChange = "";
String currentChange = "";

@Override
public void onCreate() {
    super.onCreate();
    Log.i("firebase", "it started");
    SharedPreferences settings = getSharedPreferences(PREFS, 0);
    lastChange = settings.getString("lastFbInput", "");
    Log.i("lastChange", lastChange);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    currentChange = remoteMessage.getNotification().getBody();
    Log.i("from: ", remoteMessage.getFrom() + "");
    if(remoteMessage.getData().size()>0)
        Log.i("payload: ", remoteMessage.getData().toString());

    if(remoteMessage.getNotification() != null)
        Log.i("message body: ",  remoteMessage.getNotification().getBody());

    if(!lastChange.equals("")) {
        Log.i("equals", "1");
        if (!lastChange.equals(currentChange)) {
            showNotification(remoteMessage.getNotification().getBody());
            Log.i("equals", "2");
        }
    }
    else
    {
        showNotification(remoteMessage.getNotification().getBody());
        Log.i("equals", "3");
    }

}

My problem is that the service just doesn't even run the showNotification method. Can anyone suggest a solution to that?

This is the expected behavior . When your app is in background, the notification will be handled by Android automatically. From the docs :

onMessageReceived is provided for most message types, with the following exceptions:

  • Notifications delivered when your app is in the background . In this case, the notification is delivered to the device's system tray. A user tap on a notification opens the app launcher by default.
  • Messages with both notification and data payload, both background and foreground . In this case, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

You probably have both notification and data in your payload. To only have your app handle the notifications (in onMessageReceived() ), you should use a data - only message payload. See the Message Types docs for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM