ارسال پیام به چندین دستگاه

برای هدف قرار دادن یک پیام به چندین دستگاه، از پیام‌رسانی موضوع استفاده کنید. این ویژگی به شما امکان می دهد پیامی را به چندین دستگاهی که موضوع خاصی را انتخاب کرده اند ارسال کنید.

این آموزش بر ارسال پیام‌های موضوعی از سرور برنامه شما با استفاده از Admin SDK یا REST API برای FCM، و دریافت و مدیریت آنها در یک برنامه اندروید تمرکز دارد. ما مدیریت پیام را برای برنامه‌های پس‌زمینه و پیش‌زمینه پوشش خواهیم داد. تمام مراحل برای رسیدن به این هدف، از راه‌اندازی تا تأیید، پوشش داده شده است.

SDK را تنظیم کنید

اگر یک برنامه کلاینت Android برای FCM راه‌اندازی کرده باشید یا مراحل ارسال اولین پیام خود را انجام داده باشید، این بخش ممکن است مراحلی را پوشش دهد که قبلاً انجام داده‌اید.

قبل از اینکه شروع کنی

  • اندروید استودیو را به آخرین نسخه خود نصب یا به روز کنید.

  • اطمینان حاصل کنید که پروژه شما این شرایط را برآورده می کند:

    • سطح 19 API (KitKat) یا بالاتر را هدف قرار می دهد
    • از اندروید 4.4 یا بالاتر استفاده می کند
    • از Jetpack (AndroidX) استفاده می‌کند، که شامل برآورده کردن الزامات نسخه است:
      • com.android.tools.build:gradle v7.3.0 یا جدیدتر
      • compileSdkVersion 28 یا بالاتر
  • یک دستگاه فیزیکی راه اندازی کنید یا از یک شبیه ساز برای اجرای برنامه خود استفاده کنید.
    توجه داشته باشید که Firebase SDK با وابستگی به خدمات Google Play به دستگاه یا شبیه ساز نیاز دارد که سرویس های Google Play را نصب کرده باشد.

  • با استفاده از حساب Google خود وارد Firebase شوید .

اگر قبلاً پروژه Android ندارید و فقط می‌خواهید یک محصول Firebase را امتحان کنید، می‌توانید یکی از نمونه‌های شروع سریع ما را دانلود کنید.

یک پروژه Firebase ایجاد کنید

قبل از اینکه بتوانید Firebase را به برنامه Android خود اضافه کنید، باید یک پروژه Firebase برای اتصال به برنامه Android خود ایجاد کنید. برای کسب اطلاعات بیشتر در مورد پروژه های Firebase ، از Understand Firebase Projects دیدن کنید.

برنامه خود را با Firebase ثبت کنید

برای استفاده از Firebase در برنامه Android خود، باید برنامه خود را در پروژه Firebase خود ثبت کنید. ثبت برنامه شما اغلب "افزودن" برنامه شما به پروژه شما نامیده می شود.

  1. به کنسول Firebase بروید.

  2. در مرکز صفحه نمای کلی پروژه، روی نماد Android ( ) یا افزودن برنامه کلیک کنید تا گردش کار راه اندازی راه اندازی شود.

  3. نام بسته برنامه خود را در قسمت نام بسته Android وارد کنید.

  4. (اختیاری) اطلاعات دیگر برنامه را وارد کنید: نام مستعار برنامه و گواهی امضای اشکال زدایی SHA-1 .

  5. روی ثبت برنامه کلیک کنید.

یک فایل پیکربندی Firebase اضافه کنید

  1. فایل پیکربندی Android Firebase ( google-services.json ) را دانلود و سپس به برنامه خود اضافه کنید:

    1. برای دریافت فایل پیکربندی Android Firebase خود، روی Download google-services.json کلیک کنید.

    2. فایل پیکربندی خود را به پوشه اصلی ماژول (سطح برنامه) برنامه خود منتقل کنید.

  2. برای دسترسی به مقادیر موجود در فایل پیکربندی google-services.json خود برای Firebase SDK، به افزونه Gradle خدمات Google ( google-services ) نیاز دارید.

    1. در فایل Gradle سطح ریشه (سطح پروژه) خود ( <project>/build.gradle.kts یا <project>/build.gradle )، افزونه خدمات Google را به عنوان یک وابستگی اضافه کنید:

      Kotlin

      plugins {
        id("com.android.application") version "7.3.0" apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id("com.google.gms.google-services") version "4.4.1" apply false
      }
      

      Groovy

      plugins {
        id 'com.android.application' version '7.3.0' apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id 'com.google.gms.google-services' version '4.4.1' apply false
      }
      
    2. در فایل Gradle ماژول (سطح برنامه) خود (معمولا <project>/<app-module>/build.gradle.kts یا <project>/<app-module>/build.gradle )، افزونه خدمات Google را اضافه کنید:

      Kotlin

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

      Groovy

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

SDK های Firebase را به برنامه خود اضافه کنید

  1. در فایل Gradle ماژول (سطح برنامه) خود (معمولا <project>/<app-module>/build.gradle.kts یا <project>/<app-module>/build.gradle )، وابستگی را برای Firebase Cloud اضافه کنید. کتابخانه پیام رسانی برای اندروید. توصیه می‌کنیم از Firebase Android BoM برای کنترل نسخه‌سازی کتابخانه استفاده کنید.

    برای تجربه بهینه با Firebase Cloud Messaging، توصیه می‌کنیم Google Analytics را در پروژه Firebase خود فعال کنید و Firebase SDK برای Google Analytics را به برنامه خود اضافه کنید.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.8.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 ، برنامه شما همیشه از نسخه‌های سازگار کتابخانه‌های Firebase Android استفاده می‌کند.

    (جایگزین) وابستگی های کتابخانه Firebase را بدون استفاده از BoM اضافه کنید

    اگر تصمیم گرفتید از Firebase BoM استفاده نکنید، باید هر نسخه کتابخانه Firebase را در خط وابستگی آن مشخص کنید.

    توجه داشته باشید که اگر از چندین کتابخانه Firebase در برنامه خود استفاده می کنید، ما قویاً توصیه می کنیم از BoM برای مدیریت نسخه های کتابخانه استفاده کنید، که تضمین می کند همه نسخه ها سازگار هستند.

    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.4.1")
        implementation("com.google.firebase:firebase-analytics:21.6.1")
    }
    
    به دنبال یک ماژول کتابخانه خاص کاتلین هستید؟ از اکتبر 2023 (Firebase BoM 32.5.0) ، هم توسعه دهندگان Kotlin و هم جاوا می توانند به ماژول کتابخانه اصلی وابسته باشند (برای جزئیات، به سؤالات متداول در مورد این ابتکار مراجعه کنید).

  2. پروژه اندروید خود را با فایل های Gradle همگام سازی کنید.

اشتراک برنامه مشتری در یک موضوع

برنامه های مشتری می توانند در هر موضوع موجود مشترک شوند یا می توانند موضوع جدیدی ایجاد کنند. هنگامی که یک برنامه مشتری در نام موضوع جدیدی مشترک می شود (نامی که قبلاً برای پروژه Firebase شما وجود ندارد)، موضوع جدیدی با آن نام در FCM ایجاد می شود و هر مشتری می تواند متعاقباً در آن مشترک شود.

برای اشتراک در یک موضوع، برنامه مشتری Firebase Cloud Messaging subscribeToTopic() با نام موضوع FCM فرا می‌خواند. این روش یک Task را برمی‌گرداند که می‌تواند توسط شنونده تکمیل برای تعیین اینکه آیا اشتراک موفق بوده است یا خیر استفاده کند:

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

برای لغو اشتراک، برنامه مشتری Firebase Cloud Messaging را با نام موضوع unsubscribeFromTopic() فرا می خواند.

دریافت و مدیریت پیام های موضوعی

FCM پیام های موضوعی را به همان روشی که سایر پیام های پایین دستی ارائه می دهد.

برای دریافت پیام، از سرویسی استفاده کنید که FirebaseMessagingService را گسترش دهد. سرویس شما باید تماس‌های onMessageReceived و onDeletedMessages را لغو کند.

بسته به تأخیرهای پیش از تماس با onMessageReceived ، از جمله تأخیرهای سیستم عامل، زمان راه‌اندازی برنامه، مسدود شدن رشته اصلی توسط عملیات‌های دیگر، یا تماس‌های قبلی onMessageReceived » که بیش از حد طولانی شده است، پنجره زمانی برای مدیریت یک پیام ممکن است کمتر از 20 ثانیه باشد. پس از آن زمان، رفتارهای مختلف سیستم عامل مانند حذف فرآیند اندروید یا محدودیت های اجرای پس زمینه اندروید 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 نماد برنامه را به رنگ سفید نمایش می‌دهد.

لغو روی onMessageReceived

با نادیده گرفتن روش FirebaseMessagingService.onMessageReceived ، می توانید اقداماتی را بر اساس شی RemoteMessage دریافتی انجام دهید و داده پیام را دریافت کنید:

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

در برخی شرایط، FCM ممکن است پیامی را ارائه نکند. این زمانی اتفاق می‌افتد که پیام‌های زیادی (بیش از 100) برای برنامه شما در زمان اتصال دستگاه خاص در انتظار آن باشد یا اگر دستگاه بیش از یک ماه است که به FCM متصل نشده باشد. در این موارد، ممکن است یک پاسخ به FirebaseMessagingService.onDeletedMessages() دریافت کنید، زمانی که نمونه برنامه این پاسخ تماس را دریافت می کند، باید یک همگام سازی کامل با سرور برنامه شما انجام دهد. اگر در طی 4 هفته گذشته پیامی برای برنامه در آن دستگاه ارسال نکرده باشید، FCM با onDeletedMessages() تماس نخواهد گرفت.

پیام‌های اعلان را در یک برنامه پس‌زمینه مدیریت کنید

وقتی برنامه شما در پس‌زمینه است، Android پیام‌های اعلان را به سینی سیستم هدایت می‌کند. یک ضربه کاربر بر روی اعلان، راه‌انداز برنامه را به‌طور پیش‌فرض باز می‌کند.

این شامل پیام‌هایی می‌شود که هم شامل اعلان و هم بار داده (و همه پیام‌های ارسال شده از کنسول اعلان‌ها) هستند. در این موارد، اعلان به سینی سیستم دستگاه تحویل داده می‌شود و محموله داده‌ها بر اساس هدف فعالیت راه‌انداز شما تحویل داده می‌شود.

برای اطلاعات بیشتر در مورد تحویل پیام به برنامه خود، به داشبورد گزارش FCM مراجعه کنید، که تعداد پیام‌های ارسال شده و باز شده در دستگاه‌های Apple و Android را به همراه داده‌های «impressions» (اعلان‌هایی که کاربران مشاهده می‌کنند) را برای برنامه‌های Android ثبت می‌کند.

ساخت درخواست های ارسال

پس از ایجاد یک موضوع، یا با اشتراک نمونه‌های برنامه مشتری در موضوع سمت سرویس گیرنده یا از طریق API سرور ، می‌توانید پیام‌هایی را به موضوع ارسال کنید. اگر این اولین باری است که درخواست ارسال درخواست برای 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);
  });

جاوا

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

پایتون

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

سی شارپ

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

باقی مانده

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

جاوا

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

پایتون

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

سی شارپ

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

باقی مانده

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

مراحل بعدی

  • می‌توانید از سرور خود برای اشتراک نمونه‌های برنامه مشتری در موضوعات و انجام سایر وظایف مدیریتی استفاده کنید. به مدیریت اشتراک موضوع در سرور مراجعه کنید.