Android पर किसी विषय के बारे में मैसेज भेजने की सुविधा

पब्लिश/सदस्यता मॉडल पर आधारित FCM विषय के हिसाब से मैसेज भेजने की सुविधा की मदद से, एक से ज़्यादा डिवाइसों पर मैसेज भेजा जा सकता है. हालांकि, इसके लिए ज़रूरी है कि उन डिवाइसों पर किसी विषय के लिए ऑप्ट-इन किया गया हो. ज़रूरत के मुताबिक विषय के मैसेज लिखें. इसके बाद, FCM मैसेज को सही डिवाइसों पर भरोसेमंद तरीके से राउट और डिलीवर करता है.

उदाहरण के लिए, ज्वार का पूर्वानुमान बताने वाले किसी स्थानीय ऐप्लिकेशन के उपयोगकर्ता, "ज्वारीय धाराओं की चेतावनियां" विषय के लिए ऑप्ट-इन कर सकते हैं. साथ ही, वे तय किए गए इलाकों में खारे पानी में मछली पकड़ने के लिए सबसे सही स्थितियों की सूचनाएं पा सकते हैं. खेल-कूद से जुड़े किसी ऐप्लिकेशन के उपयोगकर्ता, अपनी पसंदीदा टीमों के लाइव गेम के स्कोर अपने-आप अपडेट होने की सुविधा के लिए सदस्यता ले सकते हैं.

विषयों के बारे में इन बातों का ध्यान रखें:

  • विषय के हिसाब से मैसेज भेजने की सुविधा, मौसम या सार्वजनिक तौर पर उपलब्ध अन्य जानकारी जैसे कॉन्टेंट के लिए सबसे सही है.
  • विषय के हिसाब से भेजे जाने वाले मैसेज, इंतज़ार के समय के बजाय थ्रूपुट के लिए ऑप्टिमाइज़ किए जाते हैं. एक डिवाइस या डिवाइसों के छोटे ग्रुप को तेज़ी से और सुरक्षित तरीके से मैसेज डिलीवर करने के लिए, मैसेज को रजिस्ट्रेशन टोकन के हिसाब से टारगेट करें, न कि विषयों के हिसाब से.
  • अगर आपको हर उपयोगकर्ता को कई डिवाइसों पर मैसेज भेजने हैं, तो इन मामलों में डिवाइस ग्रुप मैसेजिंग का इस्तेमाल करें.
  • विषय के हिसाब से मैसेज भेजने की सुविधा, हर विषय के लिए असीमित सदस्यताओं के साथ काम करती है. हालाँकि, FCM इन देशों/इलाकों में सीमाएं लागू करता है:
    • किसी ऐप्लिकेशन के एक इंस्टेंस को 2,000 से ज़्यादा विषयों के लिए सदस्यता नहीं ली जा सकती.
    • अगर ऐप्लिकेशन इंस्टेंस की सदस्यता लेने के लिए, बैच इंपोर्ट का इस्तेमाल किया जा रहा है, तो हर अनुरोध में ज़्यादा से ज़्यादा 1,000 ऐप्लिकेशन इंस्टेंस शामिल किए जा सकते हैं.
    • हर प्रोजेक्ट के लिए, नई सदस्यताओं की संख्या सीमित होती है. अगर कम समय में सदस्यता के लिए बहुत ज़्यादा अनुरोध भेजे जाते हैं, तो FCM सर्वर, 429 RESOURCE_EXHAUSTED ("कोटा खत्म हो गया") जवाब देगा. एक्स्पोनेंशियल बैकऑफ़ के साथ फिर से कोशिश करें.

क्लाइंट ऐप्लिकेशन को किसी विषय की सदस्यता लेना

क्लाइंट ऐप्लिकेशन, किसी भी मौजूदा विषय की सदस्यता ले सकते हैं या वे कोई नया विषय बना सकते हैं. जब कोई क्लाइंट ऐप्लिकेशन, किसी नए विषय के नाम की सदस्यता लेता है (ऐसा नाम जो आपके Firebase प्रोजेक्ट के लिए पहले से मौजूद नहीं है), तो उस नाम का एक नया विषय FCM में बन जाता है. इसके बाद, कोई भी क्लाइंट उसकी सदस्यता ले सकता है.

किसी विषय की सदस्यता लेने के लिए, क्लाइंट ऐप्लिकेशन Firebase Cloud Messaging subscribeToTopic() को FCM विषय के नाम के साथ कॉल करता है. यह तरीका Task दिखाता है. इसका इस्तेमाल पूरा होने की सूचना देने वाले लिसनर यह तय करने के लिए कर सकते हैं कि सदस्यता ली गई है या नहीं:

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

सदस्यता छोड़ने के लिए, क्लाइंट ऐप्लिकेशन Firebase Cloud Messaging unsubscribeFromTopic() को विषय के नाम के साथ कॉल करता है.

सर्वर पर विषय की सदस्यताएं मैनेज करना

Firebase Admin SDK की मदद से, सर्वर साइड से विषय को मैनेज करने से जुड़े बुनियादी टास्क किए जा सकते हैं. रजिस्ट्रेशन टोकन की मदद से, सर्वर लॉजिक का इस्तेमाल करके एक साथ कई क्लाइंट ऐप्लिकेशन इंस्टेंस की सदस्यता ली और छोड़ी जा सकती है.

क्लाइंट ऐप्लिकेशन इंस्टेंस को किसी भी मौजूदा विषय की सदस्यता दी जा सकती है. इसके अलावा, नया विषय भी बनाया जा सकता है. जब किसी क्लाइंट ऐप्लिकेशन को किसी नए विषय (ऐसा विषय जो आपके Firebase प्रोजेक्ट के लिए पहले से मौजूद नहीं है) की सदस्यता लेने के लिए एपीआई का इस्तेमाल किया जाता है, तो उस नाम का एक नया विषय FCM में बनाया जाता है. इसके बाद, कोई भी क्लाइंट उसकी सदस्यता ले सकता है.

Firebase Admin SDK के सदस्यता तरीके में रजिस्ट्रेशन टोकन की सूची पास की जा सकती है, ताकि संबंधित डिवाइसों को किसी विषय की सदस्यता मिल सके:

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

शुरू करें

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

Admin FCM API की मदद से, डिवाइसों को किसी विषय से सदस्यता छोड़ने की अनुमति भी दी जा सकती है. इसके लिए, रजिस्ट्रेशन टोकन को सही तरीके से पास करें:

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

शुरू करें

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

subscribeToTopic() और unsubscribeFromTopic() तरीकों से, FCM से मिले जवाब वाला ऑब्जेक्ट मिलता है. अनुरोध में दिए गए रजिस्ट्रेशन टोकन की संख्या चाहे जितनी भी हो, जवाब का फ़ॉर्मैट एक जैसा होता है.

गड़बड़ी होने पर (जैसे, पुष्टि नहीं हो पाना, अमान्य टोकन या विषय वगैरह), इन तरीकों से गड़बड़ी होती है. गड़बड़ी के कोड की पूरी सूची देखने के लिए, Admin FCM API से जुड़ी गड़बड़ियां देखें. इसमें गड़बड़ियों के बारे में जानकारी और उन्हें ठीक करने का तरीका भी शामिल है.

विषय के हिसाब से मैसेज पाना और उन्हें मैनेज करना

FCM विषय के मैसेज उसी तरह डिलीवर करता है जिस तरह अन्य डाउनस्ट्रीम मैसेज डिलीवर किए जाते हैं.

मैसेज पाने के लिए, ऐसी सेवा का इस्तेमाल करें जो FirebaseMessagingService को एक्सटेंड करती हो. आपकी सेवा को onMessageReceived और onDeletedMessages कॉलबैक को ओवरराइड करना चाहिए.

मैसेज को हैंडल करने के लिए, 20 सेकंड से कम समय मिल सकता है. ऐसा onMessageReceived को कॉल करने से पहले होने वाली देरी की वजह से होता है. जैसे, ओएस में देरी, ऐप्लिकेशन के स्टार्टअप में लगने वाला समय, मुख्य थ्रेड का अन्य कार्रवाइयों से ब्लॉक होना या पिछले onMessageReceived कॉल में ज़्यादा समय लगना. इसके बाद, ओएस के अलग-अलग फ़ंक्शन काम करने लगते हैं. जैसे, Android की प्रोसेस किलिंग या Android O की बैकग्राउंड में ऐप्लिकेशन चलाने की सीमाएं. इनकी वजह से, आपको काम पूरा करने में समस्या आ सकती है.

onMessageReceived की सुविधा, ज़्यादातर तरह के मैसेज के लिए उपलब्ध है. हालांकि, इन मैसेज के लिए यह सुविधा उपलब्ध नहीं है:

  • ऐप्लिकेशन के बैकग्राउंड में होने पर डिलीवर किए गए सूचना वाले मैसेज. इस मामले में, सूचना को डिवाइस की सिस्टम ट्रे में डिलीवर किया जाता है. जब कोई उपयोगकर्ता किसी सूचना पर टैप करता है, तो ऐप्लिकेशन लॉन्चर डिफ़ॉल्ट रूप से खुल जाता है.

  • बैकग्राउंड में सूचना और डेटा पेलोड, दोनों वाले मैसेज मिलने पर. इस मामले में, सूचना को डिवाइस की सिस्टम ट्रे में भेजा जाता है. साथ ही, डेटा पेलोड को आपके लॉन्चर ऐक्टिविटी के इंटेंट के एक्स्ट्रा में भेजा जाता है.

सारांश में:

ऐप्लिकेशन का स्टेटस सूचना डेटा दोनों
फ़ोरग्राउंड onMessageReceived onMessageReceived onMessageReceived
बैकग्राउंड सिस्टम ट्रे onMessageReceived सूचना: सिस्टम ट्रे
डेटा: इंटेंट के एक्स्ट्रा में.
मैसेज टाइप के बारे में ज़्यादा जानने के लिए, सूचनाएं और डेटा मैसेज लेख पढ़ें.

ऐप्लिकेशन मेनिफ़ेस्ट में बदलाव करना

FirebaseMessagingService का इस्तेमाल करने के लिए, आपको अपने ऐप्लिकेशन के मेनिफ़ेस्ट में यह जानकारी जोड़नी होगी:

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

इसके अलावा, हमारा सुझाव है कि सूचनाओं को अपनी पसंद के मुताबिक बनाने के लिए, डिफ़ॉल्ट वैल्यू सेट करें. आपके पास कस्टम डिफ़ॉल्ट आइकॉन और कस्टम डिफ़ॉल्ट रंग तय करने का विकल्प होता है. ये आइकॉन और रंग तब लागू होते हैं, जब सूचना के पेलोड में बराबर वैल्यू सेट नहीं की जाती हैं.

कस्टम डिफ़ॉल्ट आइकॉन और कस्टम रंग सेट करने के लिए, इन लाइनों को application टैग में जोड़ें:

<!-- 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, इनके लिए कस्टम डिफ़ॉल्ट आइकॉन दिखाता है

Android, इन कामों के लिए पसंद के मुताबिक सेट किए गए डिफ़ॉल्ट रंग का इस्तेमाल करता है

  • सूचनाएं कंपोज़ करने की सुविधा से भेजे गए सभी सूचना वाले मैसेज.
  • सूचना देने वाला ऐसा कोई भी मैसेज जिसमें सूचना के पेलोड में रंग साफ़ तौर पर सेट नहीं किया गया है.

अगर कस्टम डिफ़ॉल्ट आइकॉन सेट नहीं किया गया है और सूचना के पेलोड में कोई आइकॉन सेट नहीं किया गया है, तो Android, ऐप्लिकेशन का आइकॉन दिखाता है. यह आइकॉन सफ़ेद रंग में रेंडर किया जाता है.

onMessageReceived को बदलें

FirebaseMessagingService.onMessageReceived तरीके को बदलकर, आपको मिले RemoteMessage ऑब्जेक्ट के आधार पर कार्रवाइयां की जा सकती हैं. साथ ही, मैसेज का डेटा पाया जा सकता है:

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

onDeletedMessages को बदलें

कुछ मामलों में, FCM मैसेज नहीं भेज सकता. ऐसा तब होता है, जब किसी डिवाइस पर आपका ऐप्लिकेशन कनेक्ट होता है और उस समय 100 से ज़्यादा मैसेज पेंडिंग होते हैं. इसके अलावा, ऐसा तब भी हो सकता है, जब डिवाइस एक महीने से ज़्यादा समय से FCM से कनेक्ट न हुआ हो. इन मामलों में, आपको FirebaseMessagingService.onDeletedMessages() पर कॉलबैक मिल सकता है जब ऐप्लिकेशन इंस्टेंस को यह कॉलबैक मिलता है, तो उसे आपके ऐप्लिकेशन सर्वर के साथ पूरा सिंक करना चाहिए. अगर आपने पिछले चार हफ़्तों में उस डिवाइस पर मौजूद ऐप्लिकेशन से कोई मैसेज नहीं भेजा है, तो FCM, onDeletedMessages() को कॉल नहीं करेगा.

बैकग्राउंड में चल रहे ऐप्लिकेशन में सूचनाएं मैनेज करना

जब आपका ऐप्लिकेशन बैकग्राउंड में होता है, तो Android सूचना वाले मैसेज को सिस्टम ट्रे में भेजता है. कोई उपयोगकर्ता जब सूचना पर टैप करता है, तो ऐप्लिकेशन लॉन्चर डिफ़ॉल्ट रूप से खुल जाता है.

इसमें ऐसे मैसेज शामिल हैं जिनमें सूचना और डेटा पेलोड, दोनों शामिल होते हैं. साथ ही, इसमें Notifications console से भेजे गए सभी मैसेज भी शामिल होते हैं. इन मामलों में, सूचना को डिवाइस की सिस्टम ट्रे में डिलीवर किया जाता है. साथ ही, डेटा पेलोड को आपके लॉन्चर ऐक्टिविटी के इंटेंट के एक्स्ट्रा में डिलीवर किया जाता है.

अपने ऐप्लिकेशन पर मैसेज डिलीवर होने की जानकारी पाने के लिए, FCM रिपोर्टिंग डैशबोर्ड देखें. यह डैशबोर्ड, Apple और Android डिवाइसों पर भेजे गए और खोले गए मैसेज की संख्या रिकॉर्ड करता है. साथ ही, Android ऐप्लिकेशन के लिए "इंप्रेशन" (उपयोगकर्ताओं को दिखने वाली सूचनाएं) का डेटा भी रिकॉर्ड करता है.

अनुरोध भेजने की सुविधा बनाना

विषय बनाने के बाद, उस विषय पर मैसेज भेजे जा सकते हैं. विषय बनाने के लिए, क्लाइंट ऐप्लिकेशन के इंस्टेंस को क्लाइंट साइड पर विषय की सदस्यता लें या सर्वर एपीआई का इस्तेमाल करें. अगर आपको FCM के लिए पहली बार अनुरोध भेजने हैं, तो आपके सर्वर एनवायरमेंट और FCM के बारे में जानकारी देने वाली गाइड देखें. इसमें बैकग्राउंड और सेटअप से जुड़ी ज़रूरी जानकारी दी गई है.

बैकएंड पर, मैसेज भेजने के लॉजिक में, विषय का नाम इस तरह डालें:

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)

शुरू करें

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

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

विषयों के कॉम्बिनेशन को मैसेज भेजने के लिए, शर्त तय करें. यह एक बूलियन एक्सप्रेशन होता है, जो टारगेट किए गए विषयों के बारे में बताता है. उदाहरण के लिए, यहां दी गई शर्त के हिसाब से, उन डिवाइसों को मैसेज भेजे जाएंगे जिन्होंने TopicA और TopicB या TopicC की सदस्यता ली है:

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

FCM सबसे पहले, ब्रैकेट में दी गई शर्तों का आकलन करता है. इसके बाद, एक्सप्रेशन का आकलन बाएं से दाएं करता है. ऊपर दिए गए एक्सप्रेशन में, किसी एक विषय की सदस्यता लेने वाले उपयोगकर्ता को मैसेज नहीं मिलता. इसी तरह, TopicA की सदस्यता न लेने वाले उपयोगकर्ता को मैसेज नहीं मिलता. इन कॉम्बिनेशन को यह सुविधा मिलती है:

  • TopicA और TopicB
  • TopicA और TopicC

शर्त वाले एक्सप्रेशन में ज़्यादा से ज़्यादा पांच विषयों को शामिल किया जा सकता है.

किसी शर्त के हिसाब से मैसेज भेजने के लिए:

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)

शुरू करें

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

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

अगले चरण