Messaggistica tematica su Android

In base al modello di pubblicazione/sottoscrizione, la messaggistica degli argomenti FCM ti consente di inviare un messaggio a più dispositivi che hanno aderito a un particolare argomento. Componi i messaggi di argomento secondo necessità e FCM gestisce l'instradamento e la consegna del messaggio in modo affidabile ai dispositivi giusti.

Ad esempio, gli utenti di un'app di previsione delle maree locali potrebbero aderire a un argomento "avvisi sulle correnti di marea" e ricevere notifiche sulle condizioni ottimali di pesca in acqua salata in aree specifiche. Gli utenti di un'app sportiva potrebbero abbonarsi agli aggiornamenti automatici dei risultati delle partite in diretta per le loro squadre preferite.

Alcune cose da tenere a mente sugli argomenti:

  • La messaggistica per argomento è più adatta per contenuti quali meteo o altre informazioni disponibili pubblicamente.
  • I messaggi degli argomenti sono ottimizzati per la velocità effettiva piuttosto che per la latenza . Per un recapito rapido e sicuro a singoli dispositivi o piccoli gruppi di dispositivi, indirizza i messaggi ai token di registrazione e non agli argomenti.
  • Se devi inviare messaggi a più dispositivi per utente , prendi in considerazione la messaggistica di gruppo di dispositivi per questi casi d'uso.
  • La messaggistica per argomento supporta abbonamenti illimitati per ciascun argomento. Tuttavia, FCM applica limiti in queste aree:
    • È possibile sottoscrivere un'istanza dell'app a non più di 2000 argomenti.
    • Se utilizzi l'importazione batch per sottoscrivere istanze dell'app, ogni richiesta è limitata a 1000 istanze dell'app.
    • La frequenza dei nuovi abbonamenti è limitata per progetto. Se invii troppe richieste di abbonamento in un breve periodo di tempo, i server FCM risponderanno con una risposta 429 RESOURCE_EXHAUSTED ("quota superata"). Riprova con backoff esponenziale.

Sottoscrivere l'app client a un argomento

Le app client possono sottoscrivere qualsiasi argomento esistente oppure possono creare un nuovo argomento. Quando un'app client si iscrive a un nuovo nome di argomento (uno che non esiste già per il tuo progetto Firebase), viene creato un nuovo argomento con quel nome in FCM e qualsiasi client può successivamente iscriversi ad esso.

Per sottoscrivere un argomento, l'app client chiama Firebase Cloud MessagingscribeToTopic subscribeToTopic() con il nome dell'argomento FCM. Questo metodo restituisce un Task , che può essere utilizzato da un ascoltatore di completamento per determinare se la sottoscrizione è riuscita:

Kotlin+KTX

Firebase.messaging.subscribeToTopic("weather")
    .addOnCompleteListener { task ->
        var msg = "Subscribed"
        if (!task.isSuccessful) {
            msg = "Subscribe failed"
        }
        Log.d(TAG, msg)
        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
    }

Java

FirebaseMessaging.getInstance().subscribeToTopic("weather")
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                String msg = "Subscribed";
                if (!task.isSuccessful()) {
                    msg = "Subscribe failed";
                }
                Log.d(TAG, msg);
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

Per annullare l'iscrizione, l'app client chiama Firebase Cloud Messaging unsubscribeFromTopic() con il nome dell'argomento.

Gestire le sottoscrizioni agli argomenti sul server

Firebase Admin SDK ti consente di eseguire attività di base di gestione degli argomenti dal lato server. Dati i relativi token di registrazione, puoi sottoscrivere e annullare la sottoscrizione di istanze dell'app client in blocco utilizzando la logica del server.

Puoi sottoscrivere istanze dell'app client a qualsiasi argomento esistente oppure puoi creare un nuovo argomento. Quando utilizzi l'API per iscrivere un'app client a un nuovo argomento (uno che non esiste già per il tuo progetto Firebase), un nuovo argomento con quel nome viene creato in FCM e qualsiasi client può successivamente iscriversi ad esso.

Puoi passare un elenco di token di registrazione al metodo di abbonamento Firebase Admin SDK per iscrivere i dispositivi corrispondenti a un argomento:

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // ...
  'YOUR_REGISTRATION_TOKEN_n'
];

// Subscribe the devices corresponding to the registration tokens to the
// topic.
getMessaging().subscribeToTopic(registrationTokens, topic)
  .then((response) => {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully subscribed to topic:', response);
  })
  .catch((error) => {
    console.log('Error subscribing to topic:', error);
  });

Giava

// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

// Subscribe the devices corresponding to the registration tokens to the
// topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");

Pitone

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Subscribe the devices corresponding to the registration tokens to the
# topic.
response = messaging.subscribe_to_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were subscribed successfully')

Andare

// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}

// Subscribe the devices corresponding to the registration tokens to the
// topic.
response, err := client.SubscribeToTopic(ctx, registrationTokens, topic)
if err != nil {
	log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were subscribed successfully")

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};

// Subscribe the devices corresponding to the registration tokens to the
// topic
var response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");

L'API Admin FCM consente inoltre di annullare l'iscrizione dei dispositivi a un argomento passando i token di registrazione al metodo appropriato:

Node.js

// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // ...
  'YOUR_REGISTRATION_TOKEN_n'
];

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
getMessaging().unsubscribeFromTopic(registrationTokens, topic)
  .then((response) => {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully unsubscribed from topic:', response);
  })
  .catch((error) => {
    console.log('Error unsubscribing from topic:', error);
  });

Giava

// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n"
);

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");

Pitone

# These registration tokens come from the client FCM SDKs.
registration_tokens = [
    'YOUR_REGISTRATION_TOKEN_1',
    # ...
    'YOUR_REGISTRATION_TOKEN_n',
]

# Unubscribe the devices corresponding to the registration tokens from the
# topic.
response = messaging.unsubscribe_from_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were unsubscribed successfully')

Andare

// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
	"YOUR_REGISTRATION_TOKEN_1",
	// ...
	"YOUR_REGISTRATION_TOKEN_n",
}

// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
response, err := client.UnsubscribeFromTopic(ctx, registrationTokens, topic)
if err != nil {
	log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were unsubscribed successfully")

C#

// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
    "YOUR_REGISTRATION_TOKEN_1",
    // ...
    "YOUR_REGISTRATION_TOKEN_n",
};

// Unsubscribe the devices corresponding to the registration tokens from the
// topic
var response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(
    registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were unsubscribed successfully");

I metodi subscribeToTopic() e unsubscribeFromTopic() danno come risultato un oggetto contenente la risposta da FCM. Il tipo restituito ha lo stesso formato indipendentemente dal numero di token di registrazione specificati nella richiesta.

In caso di errore (fallimenti di autenticazione, token o argomento non validi ecc.) questi metodi generano un errore. Per un elenco completo dei codici di errore, incluse descrizioni e passaggi di risoluzione, consulta Errori API FCM di amministrazione .

Ricevere e gestire messaggi di argomento

FCM consegna i messaggi dell'argomento allo stesso modo degli altri messaggi downstream.

Per ricevere messaggi, utilizza un servizio che estende FirebaseMessagingService . Il tuo servizio dovrebbe sovrascrivere i callback onMessageReceived e onDeletedMessages .

L'intervallo di tempo per la gestione di un messaggio può essere inferiore a 20 secondi a seconda dei ritardi verificatisi prima della chiamata onMessageReceived , inclusi ritardi del sistema operativo, tempo di avvio dell'app, thread principale bloccato da altre operazioni o chiamate onMessageReceived precedenti che impiegano troppo tempo. Dopo tale periodo, vari comportamenti del sistema operativo, come l'interruzione del processo di Android o i limiti di esecuzione in background di Android O, potrebbero interferire con la tua capacità di completare il tuo lavoro.

onMessageReceived viene fornito per la maggior parte dei tipi di messaggio, con le seguenti eccezioni:

  • Messaggi di notifica inviati quando l'app è in background . In questo caso, la notifica viene recapitata nella barra delle applicazioni del dispositivo. Un utente che tocca una notifica apre l'icona di avvio delle app per impostazione predefinita.

  • Messaggi con notifica e payload di dati, se ricevuti in background . In questo caso, la notifica viene recapitata nella barra delle applicazioni del dispositivo e il payload dei dati viene recapitato negli extra dell'intento dell'attività di avvio.

In sintesi:

Stato dell'app Notifica Dati Entrambi
Primo piano onMessageReceived onMessageReceived onMessageReceived
Sfondo Area di notifica onMessageReceived Notifica: barra delle applicazioni
Dati: negli extra dell'intento.
Per ulteriori informazioni sui tipi di messaggi, vedere Notifiche e messaggi di dati .

Modifica il manifest dell'app

Per utilizzare FirebaseMessagingService , devi aggiungere quanto segue nel manifest dell'app:

<service
    android:name=".java.MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

Inoltre, ti consigliamo di impostare valori predefiniti per personalizzare l'aspetto delle notifiche. È possibile specificare un'icona predefinita personalizzata e un colore predefinito personalizzato che vengono applicati ogni volta che non vengono impostati valori equivalenti nel payload della notifica.

Aggiungi queste righe all'interno del tag application per impostare l'icona predefinita personalizzata e il colore personalizzato:

<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
     See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
     notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/colorAccent" />

Android visualizza l'icona predefinita personalizzata per

  • Tutti i messaggi di notifica inviati dal compositore di notifiche .
  • Qualsiasi messaggio di notifica che non imposta esplicitamente l'icona nel payload della notifica.

Android utilizza il colore predefinito personalizzato per

  • Tutti i messaggi di notifica inviati dal compositore di notifiche .
  • Qualsiasi messaggio di notifica che non imposta esplicitamente il colore nel payload della notifica.

Se non è impostata alcuna icona predefinita personalizzata e non è impostata alcuna icona nel payload delle notifiche, Android visualizza l'icona dell'applicazione resa in bianco.

Sostituisci onMessageReceived

Eseguendo l'override del metodo FirebaseMessagingService.onMessageReceived , puoi eseguire azioni basate sull'oggetto RemoteMessage ricevuto e ottenere i dati del messaggio:

Kotlin+KTX

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
    Log.d(TAG, "From: ${remoteMessage.from}")

    // Check if message contains a data payload.
    if (remoteMessage.data.isNotEmpty()) {
        Log.d(TAG, "Message data payload: ${remoteMessage.data}")

        // Check if data needs to be processed by long running job
        if (needsToBeScheduled()) {
            // For long-running tasks (10 seconds or more) use WorkManager.
            scheduleJob()
        } else {
            // Handle message within 10 seconds
            handleNow()
        }
    }

    // Check if message contains a notification payload.
    remoteMessage.notification?.let {
        Log.d(TAG, "Message Notification Body: ${it.body}")
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

Java

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use WorkManager.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

Sostituisci onDeletedMessages eliminati

In alcune situazioni, FCM potrebbe non recapitare un messaggio. Ciò si verifica quando ci sono troppi messaggi (>100) in sospeso per la tua app su un particolare dispositivo nel momento in cui si connette o se il dispositivo non si connette a FCM da più di un mese. In questi casi, potresti ricevere una richiamata a FirebaseMessagingService.onDeletedMessages() . Quando l'istanza dell'app riceve questa richiamata, dovrebbe eseguire una sincronizzazione completa con il server dell'app. Se non hai inviato un messaggio all'app su quel dispositivo nelle ultime 4 settimane, FCM non chiamerà onDeletedMessages() .

Gestisci i messaggi di notifica in un'app in background

Quando la tua app è in background, Android indirizza i messaggi di notifica nella barra delle applicazioni. Un tocco dell'utente sulla notifica apre l'avvio delle app per impostazione predefinita.

Sono inclusi i messaggi che contengono sia notifiche che payload di dati (e tutti i messaggi inviati dalla console delle notifiche). In questi casi, la notifica viene recapitata nella barra delle applicazioni del dispositivo e il payload dei dati viene recapitato negli extra dell'intento dell'attività di avvio.

Per informazioni dettagliate sulla consegna dei messaggi alla tua app, consulta il dashboard dei rapporti FCM , che registra il numero di messaggi inviati e aperti su dispositivi Apple e Android, insieme ai dati per le "impressioni" (notifiche visualizzate dagli utenti) per le app Android.

Crea richieste di invio

Dopo aver creato un argomento, sottoscrivendo le istanze dell'app client all'argomento sul lato client o tramite l' API del server , puoi inviare messaggi all'argomento. Se è la prima volta che crei richieste di invio per FCM, consulta la guida al tuo ambiente server e FCM per importanti informazioni di base e di configurazione.

Nella logica di invio sul backend, specifica il nome dell'argomento desiderato come mostrato:

Node.js

// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Giava

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Pitone

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Andare

// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Topic: topic,
}

// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";

// See documentation on defining a message payload.
var message = new Message()
{
    Data = new Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
    Topic = topic,
};

// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

RIPOSO

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

Comando cURL:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "message": {
    "topic" : "foo-bar",
    "notification": {
      "body": "This is a Firebase Cloud Messaging Topic Message!",
      "title": "FCM Message"
    }
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Per inviare un messaggio a una combinazione di argomenti, specificare una condizione , ovvero un'espressione booleana che specifica gli argomenti di destinazione. Ad esempio, la seguente condizione invierà messaggi ai dispositivi iscritti a TopicA e TopicB o TopicC :

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM valuta prima le eventuali condizioni tra parentesi, quindi valuta l'espressione da sinistra a destra. Nell'espressione precedente, un utente iscritto a un singolo argomento non riceve il messaggio. Allo stesso modo, un utente che non è iscritto a TopicA non riceve il messaggio. Queste combinazioni lo ricevono:

  • TopicA e TopicB
  • TopicA e TopicC

Puoi includere fino a cinque argomenti nell'espressione condizionale.

Per inviare a una condizione:

Node.js

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Giava

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setCondition(condition)
    .build();

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Pitone

# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Andare

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Condition: condition,
}

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
var message = new Message()
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Condition = condition,
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

RIPOSO

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
   "message":{
    "condition": "'dogs' in topics || 'cats' in topics",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message",
    }
  }
}

Comando cURL:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "FCM Message",
    "body": "This is a Firebase Cloud Messaging Topic Message!",
  },
  "condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Prossimi passi