Nhắn tin theo chủ đề trên Android

Dựa trên mô hình xuất bản/đăng ký, tính năng nhắn tin theo chủ đề FCM cho phép bạn gửi tin nhắn đến nhiều thiết bị đã chọn tham gia một chủ đề cụ thể. Bạn soạn tin nhắn chủ đề nếu cần và FCM sẽ xử lý việc định tuyến và gửi tin nhắn một cách đáng tin cậy đến đúng thiết bị.

Ví dụ: người dùng ứng dụng dự báo thuỷ triều cục bộ có thể chọn nhận chủ đề "cảnh báo dòng thuỷ triều" và nhận thông báo về điều kiện câu cá nước mặn tối ưu ở những khu vực cụ thể. Người dùng ứng dụng thể thao có thể đăng ký nhận thông tin cập nhật tự động về tỷ số của trận đấu trực tiếp của các đội họ yêu thích.

Một số điều cần lưu ý về chủ đề:

  • Tính năng nhắn tin theo chủ đề phù hợp nhất với nội dung như thời tiết hoặc các thông tin công khai khác.
  • Thông báo theo chủ đề được tối ưu hoá cho thông lượng thay vì độ trễ. Để gửi nhanh, an toàn đến các thiết bị riêng lẻ hoặc các nhóm nhỏ thiết bị, hãy nhắm mục tiêu thông báo đến mã thông báo đăng ký thay vì chủ đề.
  • Nếu bạn cần gửi thông báo cho nhiều thiết bị cho mỗi người dùng, hãy cân nhắc sử dụng tính năng nhắn tin theo nhóm thiết bị cho những trường hợp sử dụng đó.
  • Tính năng nhắn tin theo chủ đề hỗ trợ số lượt đăng ký không giới hạn cho mỗi chủ đề. Tuy nhiên, FCM thực thi các giới hạn trong những lĩnh vực sau:
    • Một phiên bản ứng dụng chỉ có thể đăng ký tối đa 2.000 chủ đề.
    • Nếu bạn đang sử dụng tính năng nhập hàng loạt để đăng ký các phiên bản ứng dụng, thì mỗi yêu cầu sẽ được giới hạn ở 1.000 phiên bản ứng dụng.
    • Tần suất đăng ký mới bị giới hạn tỷ lệ cho mỗi dự án. Nếu bạn gửi quá nhiều yêu cầu đăng ký trong một khoảng thời gian ngắn, thì các máy chủ FCM sẽ phản hồi bằng phản hồi 429 RESOURCE_EXHAUSTED ("vượt quá hạn mức"). Hãy thử lại với thời gian đợi luỹ thừa.

Đăng ký ứng dụng khách theo một chủ đề

Ứng dụng khách có thể đăng ký theo dõi bất kỳ chủ đề hiện có nào hoặc có thể tạo một chủ đề mới. Khi một ứng dụng khách đăng ký một tên chủ đề mới (tên chưa tồn tại cho dự án Firebase của bạn), một chủ đề mới của tên đó sẽ được tạo trong FCM và mọi ứng dụng sau đó có thể đăng ký chủ đề đó.

Để đăng ký một chủ đề, ứng dụng khách này sẽ gọi dịch vụ Gửi thông báo qua đám mây của Firebase subscribeToTopic() với tên chủ đề FCM. Phương thức này trả về một Task mà trình nghe hoàn thành có thể sử dụng để xác định xem gói thuê bao có thành công hay không:

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

Để huỷ đăng ký, ứng dụng khách này sẽ gọi Giải pháp gửi thông báo qua đám mây của Firebase unsubscribeFromTopic() với tên chủ đề.

Quản lý đăng ký chủ đề trên máy chủ

SDK quản trị của Firebase cho phép bạn thực hiện các thao tác quản lý chủ đề cơ bản từ phía máy chủ. Với(các) mã thông báo đăng ký của các mã này, bạn có thể đăng ký và huỷ đăng ký hàng loạt thực thể ứng dụng bằng logic máy chủ.

Bạn có thể đăng ký các phiên bản ứng dụng khách cho bất kỳ chủ đề hiện có nào hoặc tạo một chủ đề mới. Khi bạn sử dụng API để đăng ký chủ đề mới cho ứng dụng khách (chủ đề chưa tồn tại cho dự án Firebase của bạn), một chủ đề mới có tên đó sẽ được tạo trong FCM và mọi ứng dụng sau đó có thể đăng ký chủ đề này.

Bạn có thể chuyển danh sách mã thông báo đăng ký tới phương thức đăng ký SDK dành cho quản trị viên Firebase để đăng ký các thiết bị tương ứng cho một chủ đề:

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

Tiến hành

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

API FCM dành cho quản trị viên cũng cho phép bạn huỷ đăng ký thiết bị khỏi một chủ đề bằng cách chuyển mã thông báo đăng ký đến phương thức thích hợp:

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

Tiến hành

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

Các phương thức subscribeToTopic()unsubscribeFromTopic() dẫn đến một đối tượng chứa phản hồi từ FCM. Loại dữ liệu trả về có cùng định dạng bất kể số lượng mã thông báo đăng ký được chỉ định trong yêu cầu là bao nhiêu.

Trong trường hợp xảy ra lỗi (lỗi xác thực, mã thông báo hoặc chủ đề không hợp lệ, v.v.), các phương thức này sẽ dẫn đến lỗi. Để xem danh sách đầy đủ các mã lỗi, bao gồm cả nội dung mô tả và các bước giải quyết, hãy xem bài viết Lỗi API FCM dành cho quản trị viên.

Nhận và xử lý thông báo theo chủ đề

FCM gửi thông điệp theo chủ đề theo cách giống như các thông báo tiếp theo khác.

Để nhận tin nhắn, hãy dùng một dịch vụ mở rộng FirebaseMessagingService. Dịch vụ của bạn phải ghi đè lệnh gọi lại onMessageReceivedonDeletedMessages.

Khoảng thời gian xử lý thông báo có thể ngắn hơn 20 giây tuỳ thuộc vào độ trễ phát sinh trước khi gọi onMessageReceived, bao gồm cả độ trễ hệ điều hành, thời gian khởi động ứng dụng, luồng chính bị các thao tác khác chặn hoặc các lệnh gọi onMessageReceived trước đó mất quá nhiều thời gian. Sau thời gian đó, các hành vi khác nhau của hệ điều hành như loại bỏ quy trình của Android hoặc giới hạn thực thi trong nền của Android O có thể ảnh hưởng đến khả năng hoàn thành công việc của bạn.

onMessageReceived được cung cấp cho hầu hết các loại thông báo, trừ các ngoại lệ sau:

  • Gửi tin nhắn thông báo khi ứng dụng của bạn chạy trong nền. Trong trường hợp này, thông báo sẽ được gửi đến khay hệ thống của thiết bị. Theo mặc định, khi người dùng nhấn vào một thông báo, trình chạy ứng dụng sẽ mở ra.

  • Tin nhắn có cả tải trọng thông báo và tải trọng dữ liệu, khi nhận ở chế độ nền. Trong trường hợp này, thông báo sẽ được gửi đến khay hệ thống của thiết bị và tải trọng dữ liệu được phân phối trong phần bổ sung của ý định Hoạt động của trình chạy.

Tóm lại:

Trạng thái ứng dụng Thông báo Dữ liệu Cả hai
Màu nổi onMessageReceived onMessageReceived onMessageReceived
Thông tin khái quát Khay hệ thống onMessageReceived Thông báo: khay hệ thống
Dữ liệu: trong phần bổ sung của ý định.
Để biết thêm thông tin về các loại thông báo, hãy xem bài viết Thông báo và thông báo dữ liệu.

Chỉnh sửa tệp kê khai ứng dụng

Để sử dụng FirebaseMessagingService, bạn cần thêm nội dung sau vào tệp kê khai ứng dụng:

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

Ngoài ra, bạn nên đặt các giá trị mặc định để tuỳ chỉnh giao diện thông báo. Bạn có thể chỉ định một biểu tượng mặc định tuỳ chỉnh và một màu mặc định tuỳ chỉnh được áp dụng bất cứ khi nào các giá trị tương đương không được đặt trong tải trọng thông báo.

Thêm các dòng sau vào bên trong thẻ application để đặt biểu tượng và màu sắc tuỳ chỉnh mặc định:

<!-- 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 hiển thị biểu tượng mặc định tuỳ chỉnh cho

  • Tất cả thông báo được gửi từ Trình soạn thông báo.
  • Mọi nội dung thông báo không đặt biểu tượng một cách rõ ràng trong tải trọng thông báo.

Android sử dụng màu mặc định tuỳ chỉnh cho

  • Tất cả thông báo được gửi từ Trình soạn thông báo.
  • Mọi nội dung thông báo không đặt màu sắc rõ ràng trong tải trọng thông báo.

Nếu bạn không đặt biểu tượng mặc định tuỳ chỉnh và biểu tượng nào được đặt trong tải trọng thông báo, thì Android sẽ hiển thị biểu tượng ứng dụng kết xuất bằng màu trắng.

Ghi đè onMessageReceived

Bằng cách ghi đè phương thức FirebaseMessagingService.onMessageReceived, bạn có thể thực hiện các thao tác dựa trên đối tượng RemoteMessage đã nhận và nhận dữ liệu tin nhắn:

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

Ghi đè onDeletedMessages

Trong một số trường hợp, FCM có thể không gửi tin nhắn. Trường hợp này xảy ra khi có quá nhiều thông báo (>100) đang chờ xử lý cho ứng dụng của bạn trên một thiết bị cụ thể tại thời điểm kết nối hoặc nếu thiết bị chưa kết nối với FCM trong hơn 1 tháng. Trong những trường hợp này, bạn có thể nhận được lệnh gọi lại đến FirebaseMessagingService.onDeletedMessages(). Khi phiên bản ứng dụng nhận được lệnh gọi lại này, phiên bản đó sẽ đồng bộ hoá toàn bộ với máy chủ ứng dụng của bạn. Nếu bạn không gửi tin nhắn cho ứng dụng trên thiết bị đó trong vòng 4 tuần qua, thì FCM sẽ không gọi onDeletedMessages().

Xử lý tin nhắn thông báo trong ứng dụng chạy ở chế độ nền

Khi ứng dụng của bạn chạy trong nền, Android sẽ chuyển các tin nhắn thông báo đến khay hệ thống. Theo mặc định, khi người dùng nhấn vào thông báo, trình chạy ứng dụng sẽ mở ra.

Trong đó bao gồm cả các thông báo chứa cả tải trọng thông báo và dữ liệu (cũng như tất cả thông báo gửi từ Bảng điều khiển thông báo). Trong những trường hợp này, thông báo sẽ được gửi đến khay hệ thống của thiết bị và tải trọng dữ liệu được phân phối trong phần bổ sung của ý định Hoạt động của trình chạy.

Để biết thông tin chi tiết về quá trình gửi tin nhắn đến ứng dụng của bạn, hãy xem Trang tổng quan báo cáo FCM. Trang tổng quan này ghi lại số lượng tin nhắn được gửi và mở trên các thiết bị của Apple và Android, cùng với dữ liệu về "lượt hiển thị" (thông báo mà người dùng nhìn thấy) cho các ứng dụng Android.

Tạo yêu cầu gửi

Sau khi tạo một chủ đề, bằng cách đăng ký các phiên bản ứng dụng khách với chủ đề ở phía máy khách hoặc thông qua API máy chủ, bạn có thể gửi thông báo đến chủ đề. Nếu đây là lần đầu tiên bạn tạo yêu cầu gửi cho FCM, hãy xem hướng dẫn về môi trường máy chủ và FCM để biết thông tin quan trọng về nền tảng và cách thiết lập.

Trong logic gửi trên phần phụ trợ, hãy chỉ định tên chủ đề mong muốn như sau:

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)

Tiến hành

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

Kiến trúc chuyển trạng thái đại diện (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"
      }
   }
}

Lệnh 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

Để gửi thông báo đến một tổ hợp chủ đề, hãy chỉ định một điều kiện (là biểu thức boolean chỉ định các chủ đề mục tiêu). Ví dụ: điều kiện sau đây sẽ gửi thông báo đến các thiết bị đã đăng ký TopicATopicB hoặc TopicC:

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

Trước tiên, FCM sẽ đánh giá mọi điều kiện trong dấu ngoặc đơn, sau đó đánh giá biểu thức từ trái sang phải. Trong biểu thức trên, người dùng đăng ký bất kỳ chủ đề nào sẽ không nhận được thông báo. Tương tự như vậy, người dùng không đăng ký TopicA sẽ không nhận được thông báo. Những tổ hợp này nhận được nội dung:

  • TopicATopicB
  • TopicATopicC

Bạn có thể đưa tối đa 5 chủ đề vào biểu thức có điều kiện.

Để gửi đến một điều kiện:

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)

Tiến hành

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

Kiến trúc chuyển trạng thái đại diện (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",
    }
  }
}

Lệnh 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

Các bước tiếp theo