【问题标题】:GCM Send notification to many groupsGCM 向多个组发送通知
【发布时间】:2016-02-05 06:50:45
【问题描述】:

我为群消息实现了 GCM。我的情况:

  • 设备 A 和 B 在 GROUP 1 下注册。
  • 设备 C 和 D 在 GROUP 2 下注册。

参考https://developers.google.com/cloud-messaging/notifications,我可以将通知发送到 GROUP 1,但无法发送到两个组(GROUP 1 和 2)。

这是我的代码:

<?php
define( 'API_ACCESS_KEY', 'MyAPI' );

$notification_key = 'notificationKeyHere';

// prep the bundle
$msg = array
(
    'message'   => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);
$fields = array
(
    'to'    => $notification_key,
    'data'  => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;  ?>

上面的代码仅适用于发送给一个组。 所以后来我尝试了:

$notification_key = array("nKey1", "nKey2");

产生的错误:

Field "to" must be a JSON string: ["nKey1", "nKey2"] 

那么我该如何更改我的代码,以便两个组都能收到通知?

【问题讨论】:

  • 目前,就文档而言,没有直接的方式可以发送到许多组。您可以做的是单独向相关设备发送downstream message。看到这个thread
  • 谢谢。使用“registration_ids”时出现问题。看到这个thread@gerardnimo

标签: android google-cloud-messaging


【解决方案1】:

如果您要向单个设备发送消息,请使用“to”

 'to'    => $notification_key,
 'data'  => $msg

但如果您要向多个设备发送消息,请使用“registration_ids”,

$ids = array("nKey1", "nKey2");

并发送为

 'registration_ids'  => $ids,
 'data'              => $msg, 

【讨论】:

  • 我在使用“registration_ids”时遇到了一个“NotRegistered”的错误,但是使用 :"to" @yusuf-kartal 时没问题
  • 我认为这个答案解决了你的问题。对于第二个(未注册)问题,下面的链接有详细描述stackoverflow.com/q/23470252/517134
猜你喜欢
  • 2017-07-24
  • 2014-11-09
  • 1970-01-01
  • 2016-08-26
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多