GCM向许多组发送通知

时间:2016-02-05 06:50:46

标签: android google-cloud-messaging

我为群组消息传递实施GCM。我的情况:

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

参考https://developers.google.com/cloud-messaging/notifications,我可以向第1组发送通知,但无法向两个组(第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"] 

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

1 个答案:

答案 0 :(得分:0)

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

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

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

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

并发送为

 'registration_ids'  => $ids,
 'data'              => $msg, 
相关问题