7

我已在我的Android應用中實施Firebase通知。當我的應用程序正在運行時,通知將與我的自定義佈局一起顯示,但是當應用程序未運行時,通知將以默認佈局顯示。當應用程序未運行時,如何將通知佈局更改爲我的佈局。此外,我存儲共享首選項以讓用戶切換通知。但是,當應用程序沒有運行時,通知顯示無論如何。怎樣才能做到這一點?應用關閉時的Firebase通知

@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 
    if(SettingsFragment.getReceiceNotification()){ //if user wants to receive notification 

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.push_notification_layout); 

    remoteViews.setImageViewResource(R.id.push_notif_icon,R.mipmap.ic_bird_black); 

    Intent intent = new Intent(this,MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); 


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); 
    notificationBuilder.setContent(remoteViews); 
    notificationBuilder.setContentTitle("Radyo Türkkuşu"); 
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody()); 

    notificationBuilder.setAutoCancel(true); 
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher); 
    notificationBuilder.setContentIntent(pendingIntent); 
    remoteViews.setTextViewText(R.id.push_title, "Radyo Türkkuşu"); 
    remoteViews.setTextViewText(R.id.push_context, remoteMessage.getNotification().getBody()); 
    //notificationBuilder.setLights (ContextCompat.getColor(MainActivity.context, R.color.pushColor), 5000, 5000); 
    notificationManager.notify(0,notificationBuilder.build()); 
    } 

} 
+0

你的代碼在哪裏? –

+0

我在詢問技術資料,不想執行 – orkun

+0

請檢查我的答案先生。 –

回答

16

你的問題是你使用它與通知托盤。

見本link

消息使用二者通知和數據有效載荷,無論背景和前景。在這種情況下,通知將傳遞到設備的系統托盤,並且數據有效負載將以您啓動程序活動的目的附加內容傳遞。

如果使用{data:"something"}(data-message){notification:"something"}(display-message),而你的應用程序是在後臺的數據有效載荷將交付給意圖的演員,但不是到onMessageReceived() method.I假設你實現你的代碼用於顯示通知,所以當你的應用程序是在前臺onMessageReceived()是觸發器,它顯示你想要的通知,但當它不是onMessageReceived()沒有得到觸發器,而是android系統將處理它與你的通知有效載荷。您只需從服務器端代碼中刪除{notification:"something"}(display-message/notification tray)即可始終確保onMessageReceived()

對於任何人保持一提onMessageReceived()總會引發不管羯羊它沒有前景或背景,請訪問這個link

+0

您是否使用Firebase控制檯發送消息? –

+0

是的,我使用控制檯。 – orkun

+3

那就是爲什麼。您必須使用服務器端代碼來處理請求。據我所知,控制檯總是使用通知負載。 –

7

有兩種類型的FCM消息

  1. 通知消息
  2. 數據消息

從Firebase控制檯發送的郵件是通知消息。爲了在onMessageReceived()中獲取消息,使用數據消息。使用下面的代碼在服務器端發送數據通知消息

{ 
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", 
    "data" : { 
    "Nick" : "Mario", 
    "body" : "great match!", 
    "Room" : "PortugalVSDenmark" 
    }, 
} 

參考https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

0

當你的應用程序被關閉或在後臺運行您的代碼將永遠不會被觸發。看到這個:Firebase Notification

你需要做的是檢查應用程序如何啓動,點擊通知或點擊啓動器圖標。爲此,應將一些數據添加到通知中,然後在應用程序的第一次啓動活動中檢索它們。如果您可以成功檢索它們,這意味着您的應用程序是通過點擊通知啓動的,那麼您可以執行您想要的操作。

相關問題