2017-02-28 95 views
0

我使用了Firebase通知,并创建了一个扩展为FirebaseMessagingService的类。我在这个类中创建了一个方法,获取消息正文,然后根据负载显示通知。在Firebase服务在后台运行时无法创建新通知

我的问题是,这个通知只适用于我的应用程序正在运行,但是当它关​​闭时,我得到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方法。任何人都可以提出解决方案吗?

回答

1

这是预期的行为。当您的应用程序处于后台时,通知将由Android自动处理。从docs

onMessageReceived提供了大多数的消息类型,但下列情况除外:

  • 通知时,您的应用程序在后台交付。在这种情况下,通知将传递到设备的系统托盘。用户点击通知会默认打开应用程序启动器。
  • 带有通知和数据有效负载的消息,包括背景和前景。在这种情况下,通知将传递到设备的系统托盘,并且数据有效负载将以您启动程序活动的目的附加内容传递。

你可能在你的有效载荷都notificationdata。要仅让您的应用处理通知(在onMessageReceived()中),您应该使用data - 只有消息有效负载。有关更多详细信息,请参阅Message Types文档。