1
This doubt is very frequent and I’ve seen some Stack posts in English that exemplify (without being too objective) how to solve the problem. The GCM limits the sending of the same message to 1000 devices registered in a database, at once. If there are more than 1000 devices the message is not even sent. It would take a Loop that separates the records in batches of 1000 records and jumps each amount. Ex. if you have 5000 would be 5 repetitions of 1000 for the same message: Below is the PHP code I got (and it’s the same on several websites) and that limits me to this amount, someone would have some solution?
class GCM {
function __construct(){}
public function send_notification ($registatoin_ids, $data) {
require "includes/google_api_key.php";
// GOOGLE API KEY
define ("GOOGLE_API_KEY", $google_api_key);
$url = "https://android.googleapis.com/gcm/send";
$fields = array (
"registration_ids" => $registatoin_ids,
"data" => $data,
);
//var_dump($fields);
$headers = array(
"Authorization: key=".GOOGLE_API_KEY,
"Content-Type: application/json"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
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_gcm=curl_exec($ch);
if($result_gcm===FALSE) {
die("Curl failed: ".curl_error($ch));
}
curl_close($ch);
//echo $result_gcm;
}
}
// Create connection
$conn = mysqli_connect($mysqlHost, $mysqlUser, $mysqlPwd, $mysqlDbname);
// Check connection
if (!$conn) {
die ("Connection failed: " . mysqli_connect_error());
}
$result = $conn->query("SELECT * FROM tbl_notification WHERE users_android_token IS NOT NULL AND users_android_token <> ''");
$android_tokens = array();
$x = 0;
if ($result -> num_rows > 0) { // Acredito que aqui seria
// o local para inserir um laço for
// output data of each row
while($row = $result -> fetch_assoc()) {
$android_tokens[] = $row["users_android_token"];
$x++;
}
} else {
echo "";
}
$conn -> close();
$title = $_POST['title'];
$msg = $_POST['message'];
$link = $_POST['link'];
if ($android_tokens != array()) {
$gcm = new GCM();
$data = array("title" => $title,"description" => $msg,"link" => $link);
$result_android = $gcm -> send_notification($android_tokens,$data);
}
Excellent. I had already seen this suggestion in Stack in English, but not so objectively. Insert this into my script and now I must let it reach 1,000 users again. I had deleted some records to continue sending. Once I get a positive return I mark as sure.
– Leoman Alves Moitinho
Jeferson Assis, perfect your solution. Today the BD is over 1.005 and the system continues working.
– Leoman Alves Moitinho