了解 2023 年 Google I/O 大会上介绍的 Firebase 亮点。了解详情

Birden fazla cihaza mesaj gönderin

Firebase Cloud Messaging, bir mesajı birden fazla cihaza hedeflemek için iki yol sunar:

  • Belirli bir konuyu seçmiş olan birden fazla cihaza mesaj göndermenizi sağlayan konu mesajlaşması .
  • Cihaz grup mesajlaşma , tanımladığınız bir gruba ait birden fazla cihaza mesaj göndermenizi sağlar.

Bu eğitim, Admin SDK veya FCM için REST API kullanarak uygulama sunucunuzdan konu mesajları göndermeye ve bunları bir android uygulamasında alıp işlemeye odaklanır. Hem arka planlı hem de ön planlı uygulamalar için mesaj işlemeyi ele alacağız. Bunu başarmak için kurulumdan doğrulamaya kadar tüm adımlar ele alınmıştır.

SDK'yı kurun

Bu bölüm, FCM için bir Android istemci uygulaması ayarladıysanız veya İlk Mesajınızı Gönderme adımlarını uyguladıysanız, halihazırda tamamlamış olduğunuz adımları kapsayabilir.

Sen başlamadan önce

  • Android Studio'yu en son sürümüne yükleyin veya güncelleyin.

  • Projenizin şu gereksinimleri karşıladığından emin olun:

    • API seviyesi 19 (KitKat) veya üstünü hedefler
    • Android 4.4 veya üstünü kullanır
    • Bu sürüm gereksinimlerini karşılamayı içeren Jetpack (AndroidX) kullanır:
      • com.android.tools.build:gradle v3.2.1 veya üstü
      • compileSdkVersion 28 veya üstü
  • Uygulamanızı çalıştırmak için fiziksel bir cihaz kurun veya bir öykünücü kullanın.
    Google Play hizmetlerine bağımlı olan Firebase SDK'larının, cihazda veya emülatörde Google Play hizmetlerinin kurulu olmasını gerektirdiğini unutmayın.

  • Google hesabınızı kullanarak Firebase'de oturum açın .

Halihazırda bir Android projeniz yoksa ve yalnızca bir Firebase ürünü denemek istiyorsanız, hızlı başlangıç ​​örneklerimizden birini indirebilirsiniz.

Bir Firebase projesi oluşturun

Firebase'i Android uygulamanıza ekleyebilmeniz için önce Android uygulamanıza bağlanmak üzere bir Firebase projesi oluşturmanız gerekir. Firebase projeleri hakkında daha fazla bilgi edinmek için Firebase Projelerini Anlayın sayfasını ziyaret edin.

Uygulamanızı Firebase'e kaydedin

Firebase'i Android uygulamanızda kullanmak için uygulamanızı Firebase projenize kaydetmeniz gerekir. Uygulamanızı kaydettirmek genellikle uygulamanızı projenize "eklemek" olarak adlandırılır.

  1. Firebase konsoluna gidin.

  2. Kurulum iş akışını başlatmak için projeye genel bakış sayfasının ortasındaki Android simgesini ( ) veya Uygulama ekle'yi tıklayın.

  3. Android paket adı alanına uygulamanızın paket adını girin.

  4. (İsteğe bağlı) Diğer uygulama bilgilerini girin: Uygulama takma adı ve Hata ayıklama imzalama sertifikası SHA-1 .

  5. Uygulamayı kaydet'i tıklayın.

Bir Firebase yapılandırma dosyası ekleyin

  1. Firebase Android yapılandırma dosyasını ( google-services.json ) indirin ve ardından uygulamanıza ekleyin:

    1. Firebase Android yapılandırma dosyanızı edinmek için google-services.json'u indir'i tıklayın.

    2. Yapılandırma dosyanızı uygulamanızın modül (uygulama düzeyi) kök dizinine taşıyın.

  2. google-services.json yapılandırma dosyanızdaki değerlerin Firebase SDK'ları tarafından erişilebilir olması için Google services Gradle eklentisine ( google-services ) ihtiyacınız vardır.

    1. Kök düzeyinde (proje düzeyinde) Gradle dosyanıza ( <project>/build.gradle ), Google hizmetleri eklentisini bir yapı betiği bağımlılığı olarak ekleyin:

      buildscript {
      
          repositories {
            // Make sure that you have the following two repositories
            google()  // Google's Maven repository
            mavenCentral()  // Maven Central repository
          }
      
          dependencies {
            ...
      
            // Add the dependency for the Google services Gradle plugin
            classpath 'com.google.gms:google-services:4.3.15'
          }
      }
      
      allprojects {
        ...
      
        repositories {
          // Make sure that you have the following two repositories
          google()  // Google's Maven repository
          mavenCentral()  // Maven Central repository
        }
      }
      
    2. Modül (uygulama düzeyinde) Gradle dosyanıza (genellikle <project>/<app-module>/build.gradle ), Google hizmetleri eklentisini ekleyin:

      plugins {
          id 'com.android.application'
      
          // Add the Google services Gradle plugin
          id 'com.google.gms.google-services'
          ...
      }
      

Uygulamanıza Firebase SDK'ları ekleyin

  1. Modül (uygulama düzeyinde) Gradle dosyanızda (genellikle <project>/<app-module>/build.gradle ), Firebase Cloud Messaging Android kitaplığı için bağımlılığı ekleyin. Kitaplık sürüm oluşturmayı kontrol etmek için Firebase Android BoM'yi kullanmanızı öneririz.

    Firebase Cloud Messaging ile optimum bir deneyim için Firebase projenizde Google Analytics'i etkinleştirmenizi ve Google Analytics için Firebase SDK'yı uygulamanıza eklemenizi öneririz.

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-messaging'
        implementation 'com.google.firebase:firebase-analytics'
    }
    

    Firebase Android BoM'yi kullandığınızda, uygulamanız her zaman Firebase Android kitaplıklarının uyumlu sürümlerini kullanır.

    (Alternatif) BoM kullanmadan Firebase kitaplığı bağımlılıkları ekleyin

    Firebase BoM'yi kullanmamayı seçerseniz, her bir Firebase kitaplığı sürümünü bağımlılık satırında belirtmeniz gerekir.

    Uygulamanızda birden çok Firebase kitaplığı kullanıyorsanız kitaplık sürümlerini yönetmek için tüm sürümlerin uyumlu olmasını sağlayan BoM'yi kullanmanızı kesinlikle öneririz.

    dependencies {
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-messaging:23.1.2'
        implementation 'com.google.firebase:firebase-analytics:21.3.0'
    }
    

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-messaging-ktx'
        implementation 'com.google.firebase:firebase-analytics-ktx'
    }
    

    Firebase Android BoM'yi kullandığınızda, uygulamanız her zaman Firebase Android kitaplıklarının uyumlu sürümlerini kullanır.

    (Alternatif) BoM kullanmadan Firebase kitaplığı bağımlılıkları ekleyin

    Firebase BoM'yi kullanmamayı seçerseniz, her bir Firebase kitaplığı sürümünü bağımlılık satırında belirtmeniz gerekir.

    Uygulamanızda birden çok Firebase kitaplığı kullanıyorsanız kitaplık sürümlerini yönetmek için tüm sürümlerin uyumlu olmasını sağlayan BoM'yi kullanmanızı kesinlikle öneririz.

    dependencies {
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-messaging-ktx:23.1.2'
        implementation 'com.google.firebase:firebase-analytics-ktx:21.3.0'
    }
    

  2. Android projenizi Gradle dosyalarıyla senkronize edin.

İstemci uygulamasını bir konuya abone olun

İstemci uygulamaları mevcut herhangi bir konuya abone olabilir veya yeni bir konu oluşturabilir. Bir istemci uygulaması yeni bir konu adına (Firebase projeniz için zaten mevcut olmayan) abone olduğunda, FCM'de bu adla yeni bir konu oluşturulur ve daha sonra herhangi bir müşteri buna abone olabilir.

Bir konuya abone olmak için istemci uygulaması, FCM konu adıyla Firebase Cloud Messaging subscribeToTopic() çağırır. Bu yöntem, bir tamamlama dinleyicisi tarafından aboneliğin başarılı olup olmadığını belirlemek için kullanılabilen bir Task döndürür:

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

Aboneliği iptal etmek için istemci uygulaması, konu adıyla Firebase Cloud Messaging unsubscribeFromTopic() öğesini çağırır.

Konu mesajlarını alın ve işleyin

FCM, konu mesajlarını diğer aşağı akış mesajlarıyla aynı şekilde iletir.

Mesaj almak için FirebaseMessagingService öğesini genişleten bir hizmet kullanın. Hizmetiniz, onMessageReceived ve onDeletedMessages geri aramalarını geçersiz kılmalıdır. Herhangi bir mesajı aldıktan sonra 20 saniye içinde işlemelidir (Android Marshmallow'da 10 saniye). Zaman penceresi, onMessageReceived çağrısından önce oluşan işletim sistemi gecikmelerine bağlı olarak daha kısa olabilir. Bu süreden sonra, Android O'nun arka planda yürütme sınırları gibi çeşitli işletim sistemi davranışları işinizi tamamlamanızı engelleyebilir. Daha fazla bilgi için mesaj önceliği hakkındaki genel bakışımıza bakın.

onMessageReceived , aşağıdaki istisnalar dışında çoğu mesaj türü için sağlanır:

  • Uygulamanız arka planda olduğunda gönderilen bildirim mesajları . Bu durumda bildirim, cihazın sistem tepsisine iletilir. Kullanıcı bir bildirime dokunduğunda varsayılan olarak uygulama başlatıcı açılır.

  • Arka planda alındığında hem bildirim hem de veri yükü içeren mesajlar . Bu durumda, bildirim cihazın sistem tepsisine iletilir ve veri yükü, başlatıcı Etkinliğinizin amacının ekstralarında teslim edilir.

Özetle:

Uygulama durumu Bildiri Veri İkisi birden
ön plan onMessageReceived onMessageReceived onMessageReceived
Arka plan Sistem tepsisi onMessageReceived Bildirim: sistem tepsisi
Veri: amacın ekstralarında.
Mesaj türleri hakkında daha fazla bilgi için bkz. Bildirimler ve veri mesajları .

Uygulama bildirimini düzenleyin

FirebaseMessagingService kullanmak için uygulama bildiriminize aşağıdakini eklemeniz gerekir:

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

Ayrıca, bildirimlerin görünümünü özelleştirmek için varsayılan değerleri ayarlamanız önerilir. Bildirim yükünde eşdeğer değerler ayarlanmadığında uygulanan özel bir varsayılan simge ve özel bir varsayılan renk belirleyebilirsiniz.

Özel varsayılan simgeyi ve özel rengi ayarlamak için application etiketinin içine şu satırları ekleyin:

<!-- 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 için özel varsayılan simgeyi görüntüler.

  • Bildirim oluşturucusundan gönderilen tüm bildirim mesajları.
  • Bildirim yükündeki simgeyi açıkça ayarlamayan herhangi bir bildirim mesajı.

Android, için özel varsayılan rengi kullanır.

  • Bildirim oluşturucusundan gönderilen tüm bildirim mesajları.
  • Bildirim yükünde rengi açıkça ayarlamayan herhangi bir bildirim mesajı.

Bildirim yükünde hiçbir özel varsayılan simge ayarlanmamışsa ve hiçbir simge ayarlanmamışsa, Android uygulama simgesini beyaz olarak görüntüler.

onMessageReceived Geçersiz Kıl

FirebaseMessagingService.onMessageReceived yöntemini geçersiz kılarak, alınan RemoteMessage nesnesine dayalı eylemler gerçekleştirebilir ve mesaj verilerini alabilirsiniz:

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

onDeletedMessages geçersiz kıl

Bazı durumlarda, FCM bir mesaj teslim etmeyebilir. Bu, belirli bir cihaz bağlandığında uygulamanız için bekleyen çok fazla mesaj (> 100) olduğunda veya cihaz bir aydan uzun bir süredir FCM'ye bağlanmadığında meydana gelir. Bu durumlarda, FirebaseMessagingService.onDeletedMessages() için bir geri arama alabilirsiniz. Uygulama örneği bu geri aramayı aldığında, uygulama sunucunuzla tam bir eşitleme gerçekleştirmelidir. Bu cihazdaki uygulamaya son 4 hafta içinde bir mesaj göndermediyseniz, FCM onDeletedMessages() öğesini aramaz.

Bildirim mesajlarını arka planda çalışan bir uygulamada yönetin

Uygulamanız arka planda olduğunda, Android bildirim mesajlarını sistem tepsisine yönlendirir. Bildirime bir kullanıcı dokunuşu, varsayılan olarak uygulama başlatıcıyı açar.

Buna hem bildirim hem de veri yükü içeren mesajlar (ve Bildirimler konsolundan gönderilen tüm mesajlar) dahildir. Bu durumlarda bildirim, cihazın sistem tepsisine iletilir ve veri yükü, başlatıcı Etkinliğinizin amacının ekstralarında teslim edilir.

Uygulamanıza mesaj teslimi hakkında fikir edinmek için, Apple ve Android cihazlarda gönderilen ve açılan mesajların sayısını ve Android uygulamaları için "gösterimler" (kullanıcılar tarafından görülen bildirimler) verilerini kaydeden FCM raporlama panosuna bakın.

Gönderme istekleri oluşturun

İstemci uygulama örneklerini konuya istemci tarafında abone olarak veya sunucu API'si aracılığıyla bir konu oluşturduktan sonra konuya mesaj gönderebilirsiniz. FCM için ilk kez gönderme istekleri oluşturuyorsanız, önemli arka plan ve kurulum bilgileri için sunucu ortamınıza ve FCM'ye ilişkin kılavuza bakın.

Arka uçtaki gönderme mantığınızda, istediğiniz konu adını gösterildiği gibi belirtin:

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

Piton

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

Gitmek

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

DİNLENMEK

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

cURL komutu:

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

Bir konu kombinasyonuna mesaj göndermek için, hedef konuları belirten bir mantıksal ifade olan bir koşul belirtin. Örneğin, aşağıdaki koşul, TopicA ve TopicB veya TopicC abone olan cihazlara mesaj gönderir:

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

FCM önce herhangi bir koşulu parantez içinde değerlendirir ve ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya üye olan kullanıcı mesajı almamaktadır. Aynı şekilde TopicA abone olmayan bir kullanıcı mesajı almaz. Bu kombinasyonlar bunu alır:

  • TopicA ve TopicB
  • TopicA ve TopicC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz.

Bir koşula göndermek için:

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

Piton

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

Gitmek

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

DİNLENMEK

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",
    }
  }
}

cURL komutu:

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

Sonraki adımlar