tony9099
tony9099

Reputation: 4727

Sending Android push notifications one shot instead of one by one

I am trying to send push notifications to users where GCM IDs are storing in a MySQL DB. The thing is with my code, I am fetching the IDs and sending them one by one inside a while loop. If the number of users is big, that is there are lots of IDs (around 700) the server is giving an Internal Error... while once I make the number less (around 200) the code runs fine and I do not get any error.

My question is, is there a way to send the push notification one shot instead of one by one.

Below is the code I am using the send.

include ("/home/myHome/db/db.php");

$resultTokenUser = $mysqli->query ('select * from android');

if ($resultTokenUser->num_rows > 0)
{               
    while ( $row = $resultTokenUser->fetch_assoc () )
    {           
        $token = $row ['gcm_regid'];
        $registatoin_ids = array ("$token");

        $messageToSend = array (
                "notificationMessage" => "Hello",
        );

        $url = 'https://android.googleapis.com/gcm/send';

        $fields = array (
                'registration_ids' => $registatoin_ids,
                'data' => $messageToSend 
        );

        define ( "GOOGLE_API_KEY", "myKey" );
        $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 = curl_exec ( $ch );
    }
}

curl_close ( $ch );

Upvotes: 0

Views: 262

Answers (2)

lakshay
lakshay

Reputation: 1028

Yes you can send notification to up to 1000 devices in one shot . You can create an array of 1000 registration ids at once and put it in the registration_ids value of the request.

$registration_ids=array("id1", "id2",…...." Id1000");

$fields = array(
    'registration_ids' => $registatoin_ids,
    'data' => $message,
);

Upvotes: 1

MauriF
MauriF

Reputation: 682

GCM HTTP Connection Server - Source

Retrieve the registration ids from your DB as an array, and fill the $registatoin_ids array with each reg id, and send it just once.

 $registatoin_ids = array();
    for($i=0;$i<$reg_id_count;$i++) {

        array_push($registatoin_ids, $row[$i]['gcm_regid']);

    }

Upvotes: 1

Related Questions