【问题标题】:Send Push Notification on All token in database MySql在数据库 MySql 中的所有令牌上发送推送通知
【发布时间】:2017-12-22 12:27:43
【问题描述】:

我为我的应用创建了一个推送通知,它运行良好,但没有在所有设备令牌上发送通知。

首先我有一个数据库名称“成员”,它包含 id、用户名、密码、令牌

然后我创建这个 php 函数来发送通知

<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'XXXXXXXXXXXXXXXXX' );
include 'DatabaseConfig.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$checktoken = "SELECT token FROM member";
$results = $con->query($checktoken);

if ($results ->num_rows > 0) {

while($row = $results->fetch_assoc()){

$regid = array($row["token"]);
echo "" .$row["token"]. " ";
}
}else{
echo "No result";
}

// prep the bundle
$msg = array
(
    'body'  => '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'     => 'mySound',
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);
$fields = array
(
    'registration_ids'  => $regid,
    'notification'          => $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;

代码只发送到一台设备,当我尝试在浏览器中访问它时,它会显示

eY0-0uIUDsA:APA91bGmFatL_gtizFRbC9mMbagzsMalJuJ6e_O2poytaKgBTVIsyl5ogJ4-x7PlQebyu6z7ME970H9hdlZUEiLESTNPrSvcn_1PzmKh3AJiwIUZj86_fRxPt9yOpL4k3PZb7Ir6xf dPEPzRFjnIo:APA91bHBaHO8nZK2g4xF6vzvKrevNhpBRSdIb3NyWrr2PRCEyDR9cLkCZOZ28_hu5pDzdaSKkRxPY1mvYO8ZOnjEscjdKGCEv-FIdIBzrz32mof0rQSlog028kDhv7jltGjWwK7r7l- {"multicast_id":9198379759567809790,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1513945312938936%cd487dfdcd487dfd"}]}

那里有 2 个设备,但为什么它只发送到一个设备令牌?我的代码有什么修复方法吗?

供您参考 第一个设备以 eY0-0uIUDsA 开头: 第二个以 dPEPzRFjnIo 开头:

【问题讨论】:

  • 你在每个循环上覆盖$regid,所以最后只有一个设备在那里。
  • 我认为您的意思是使用$regid[] = $row["token"]; 而不是$regid = array($row["token"]);。并且不要忘记在您的 while 循环之前使用 $regid = [] 初始化变量。
  • 感谢您的帮助

标签: php android mysql push-notification


【解决方案1】:

您将在每次循环迭代时覆盖 $regid 的内容。 定义循环外的数组:

$regid = [];

if ($results ->num_rows > 0) {
    while($row = $results->fetch_assoc()){
        $regid[] = $row["token"];
        echo "" .$row["token"]. " ";
     }
 } else {
     echo "No result";
 }

另外,最好将发送通知的代码放在 if 的正分支中,只有当你得到结果时才发送它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2014-08-06
    相关资源
    最近更新 更多