2017-02-28 94 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文檔。