Firebase 通知 - 发送到用户段与发送到主题差异

Firebase Notification - send to user segment vs send to topic difference

我被分配了一个任务来使用 Firebase 来实现推送通知,但我是个新手。

查看文档:

https://firebase.google.com/docs/notifications/android/console-audience

我分不清什么情况下应该用send to user segment还是send to a topic

谁能给我一些何时使用其中一个或另一个的例子并指出区别?先谢谢 :)

Use User segements

  • 通常将推送通知发送到一组特定且有限的设备。
  • 消息传递几乎是即时的(以我的经验)。另外,我没有像之前使用 GCM 那样观察到节流。

Use Topics

  • 主题或publish/subscribe机制用于比较大的受众,信息类型为public。例如天气和新闻。
  • 主题有延迟(消息传递可能会受到限制)

用户细分

  • 您只能通过 Firebase Console. (see ).
  • 向用户群发送通知
  • 仅限于特定目标(来自您链接的docs):

    Select the message target. The dialog displays further options to refine the target based on whether you choose App/App Version, Device Language, or Users in Audience.

  • 正如您链接的 doc 中已经提到的那样:

    You can target predefined user segments or custom audiences created in Firebase Analytics.

主题

  • Token/device 不一定需要管理。
  • 订阅者数量不限。
  • 可以使用 FCM 发送到主题 API。
  • 可以通过客户端应用轻松 subscribe/unsubscribe。

恕我直言,如果您想让事情变得快速简单,请使用主题消息传递。

首先,您必须为要向其发送通知的每个设备保存令牌,我已将它们保存在 table 调用 "FCM_TOKEN" 中,然后检索令牌(我正在使用PDO) 并像这样使用 while 循环发送它们:

while($row=$statement->fetch(PDO::FETCH_BOTH))
            {
                $key = $row['Fcm_Token'];
                $headers = array(
                'Authorization:key=' .$server_key,
                'Content-Type:application/json');
                $fields = array('to'=>$key,
                    'notification'=>array('title'=>$titulo, 'body'=>$mensaje,
                        'click_action'=>'com.example.witch.gtslsac_app_1_TARGET_NOTIFICATION'
                        )); 
                        $playload=json_encode($fields);
            $curl_session = curl_init();
            curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
            curl_setopt($curl_session, CURLOPT_POST, true);
            curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
            curl_setopt($curl_session, CURLOPT_POSTFIELDS, $playload);

            $result = curl_exec($curl_session);
            echo $result;   
            }   

别忘了关闭会话 curl_close($curl_session); 这对我来说很好。