在Firebase服务在后台运行时,无法创建新的通知



我使用了firebase通知,并制作了一个扩展FirebaseMessagingService的类。我在此类中制作了一种获取消息主体的方法,然后根据有效载荷显示通知。

我的问题是,此通知仅在我的应用程序运行时起作用,但是当它关闭时,我会收到Firebase的默认通知,而不是我创建的自定义的通知。

我的服务课是:

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");
    }
}

我的问题是该服务甚至没有运行showNotification方法。谁能建议解决方案?

这是预期行为。当您的应用在后台时,通知将由Android自动处理。从文档中:

onMessageReceived针对大多数消息类型提供了以下例外:

  • 当您的应用在后台中,已发送通知。在这种情况下,将通知传递到设备的系统托盘上。用户点击通知,默认情况下打开应用启动器。
  • 带有通知和数据有效负载的消息,背景和前景。在这种情况下,通知将传递到设备的系统托盘,数据有效载荷是在发射器活动意图的附加功能中传递的。

您的有效载荷中可能同时具有notificationdata。要仅让您的应用程序处理通知(在onMessageReceived()中),您应使用data- 消息有效负载。有关更多详细信息,请参见消息类型文档。

最新更新