Messaggistica di argomenti 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 attivato un determinato argomento. Componi i messaggi dell'argomento in base alle tue esigenze e FCM gestisce il routing e la consegna affidabile del messaggio ai dispositivi giusti.

Ad esempio, gli utenti di un'app locale di previsione delle maree potrebbero attivare l'argomento "Avvisi sulle correnti di marea" e ricevere notifiche sulle condizioni ottimali per la pesca in acqua salata in aree specifiche. Gli utenti di un'app di sport potrebbero abbonarsi agli aggiornamenti automatici dei risultati in tempo reale delle partite delle loro squadre preferite.

Alcune cose da tenere a mente sugli argomenti:

  • La messaggistica per argomenti è più adatta a contenuti come il meteo o altre informazioni disponibili pubblicamente.
  • I messaggi sugli argomenti sono ottimizzati per la velocità effettiva anziché per la latenza. Per una distribuzione rapida e sicura a singoli dispositivi o piccoli gruppi di dispositivi, i messaggi di targeting ai token di registrazione, non agli argomenti.
  • Se devi inviare messaggi a più dispositivi per utente, valuta la possibilità di utilizzare la messaggistica di gruppo dei dispositivi per questi casi d'uso.
  • La messaggistica per argomento supporta un numero illimitato di sottoscrizioni per ogni argomento. Tuttavia, FCM applica limiti in queste aree:
    • Un'istanza dell'app può essere iscritta a un massimo di 2000 argomenti.
    • Se utilizzi l'importazione batch per abbonarti alle istanze dell'app, ogni richiesta è limitata a 1000 istanze dell'app.
    • La frequenza dei nuovi abbonamenti è limitata in base alla velocità per progetto. Se invii troppe richieste di iscrizione in un breve periodo di tempo, i server FCM risponderanno con una risposta 429 RESOURCE_EXHAUSTED ("quota superata"). Riprova con backoff esponenziale.

Abbonarsi a un argomento nell'app client

Le app client possono iscriversi a qualsiasi argomento esistente o crearne uno nuovo. 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.

Per sottoscrivere un argomento, l'app client chiama Firebase Cloud Messaging subscribeToTopic() con il nome dell'argomento FCM. Questo metodo restituisce un Task, che può essere utilizzato da un listener di completamento per determinare se l'abbonamento è andato a buon fine:

Kotlin

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 iscrizioni agli argomenti sul server

Firebase Admin SDK ti consente di eseguire attività di gestione di base degli argomenti dal lato server. Dato il token o i token di registrazione, puoi iscrivere e annullare l'iscrizione di istanze dell'app client in blocco utilizzando la logica del server.

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

Puoi trasmettere un elenco di token di registrazione al metodo di sottoscrizione 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);
  });

Java

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

Python

# 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')

Vai

// 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 ti consente anche 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);
  });

Java

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

Python

# 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')

Vai

// 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() restituiscono un oggetto contenente la risposta di FCM. Il tipo di restituzione ha lo stesso formato indipendentemente dal numero di token di registrazione specificati nella richiesta.

In caso di errore (autenticazioni non riuscite, token o argomento non validi e così via), questi metodi generano un errore. Per un elenco completo dei codici di errore, incluse descrizioni e passaggi per la risoluzione, consulta Errori API Admin FCM.

Ricevere e gestire i messaggi degli argomenti

FCM recapita i messaggi dell'argomento nello stesso modo degli altri messaggi downstream.

Per ricevere messaggi, utilizza un servizio che estende FirebaseMessagingService. Il tuo servizio deve eseguire l'override dei callback onMessageReceived e onDeletedMessages.

La finestra temporale per la gestione di un messaggio potrebbe essere inferiore a 20 secondi a seconda dei ritardi prima della chiamata di onMessageReceived, inclusi ritardi del sistema operativo, tempo di avvio dell'app, il thread principale bloccato da altre operazioni o chiamate onMessageReceived precedenti che richiedono troppo tempo. Dopo questo periodo di tempo, vari comportamenti del sistema operativo, come l'interruzione dei processi di Android o i limiti di esecuzione in background di Android O, potrebbero interferire con la tua capacità di completare il lavoro.

onMessageReceived è fornito per la maggior parte dei tipi di messaggi, con le seguenti eccezioni:

  • Messaggi di notifica inviati quando l'app è in background. In questo caso, la notifica viene inviata alla barra delle applicazioni del dispositivo. Quando un utente tocca una notifica, per impostazione predefinita si apre Avvio app.

  • Messaggi con payload di notifica e dati, quando ricevuti in background. In questo caso, la notifica viene inviata alla barra delle applicazioni del dispositivo e il payload di dati viene inviato negli extra dell'intent dell'attività di avvio.

In sintesi:

Stato dell'app Notifica Dati Entrambe
Primo piano onMessageReceived onMessageReceived onMessageReceived
Contesto Barra delle applicazioni onMessageReceived Notifica: barra delle notifiche
Dati: negli extra dell'intent.
Per ulteriori informazioni sui tipi di messaggi, vedi Notifiche e messaggi di dati.

Modificare 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 i valori predefiniti per personalizzare l'aspetto delle notifiche. Puoi specificare un'icona predefinita personalizzata e un colore predefinito personalizzato che vengono applicati ogni volta che i valori equivalenti non vengono impostati 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 composer delle 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 composer delle 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 di notifica, Android visualizza l'icona dell'applicazione visualizzata in bianco.

Override onMessageReceived

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

Kotlin

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.
}

Override onDeletedMessages

In alcune situazioni, FCM potrebbe non inviare un messaggio. Ciò si verifica quando ci sono troppi messaggi (>100) in attesa per la tua app su un determinato dispositivo al momento della connessione o se il dispositivo non si è connesso a FCM per più di un mese. In questi casi, potresti ricevere un callback a FirebaseMessagingService.onDeletedMessages(). Quando l'istanza dell'app riceve questo callback, deve 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().

Gestire i messaggi di notifica in un'app in background

Quando l'app è in background, Android indirizza i messaggi di notifica alla barra delle applicazioni. Quando un utente tocca la notifica, per impostazione predefinita si apre Avvio app.

Sono inclusi i messaggi che contengono sia il payload di notifica che quello di dati (e tutti i messaggi inviati dalla console Notifiche). In questi casi, la notifica viene inviata alla barra delle applicazioni del dispositivo e il payload di dati viene inviato negli extra dell'intent dell'attività del launcher.

Per informazioni sulla distribuzione dei messaggi alla tua app, consulta la dashboard dei report FCM, che registra il numero di messaggi inviati e aperti su dispositivi Apple e Android, nonché i dati relativi alle "impressioni" (notifiche visualizzate dagli utenti) per le app per Android.

Creare richieste di invio

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

Nella logica di invio del backend, specifica il nome dell'argomento che preferisci come mostrato di seguito:

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

Java

// 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);

Python

# 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)

Vai

// 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);

REST

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, specifica 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 a TopicB o TopicC:

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

FCM valuta prima le condizioni tra parentesi e poi 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 si iscrive 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);
  });

Java

// 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);

Python

# 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)

Vai

// 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);

REST

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

Passaggi successivi

  • Scopri di più sull'altro modo per inviare messaggi a più dispositivi: i messaggi di gruppo.