jason
jason

Reputation: 3962

gcm not received on a device sometime

I am using gcm service to send notification and it works fine most of the time but sometimes it does not send gcm to a device or it sends message really late .How can I fix this problem?

COde:

/**
     * Sending Push Notification
     */
    public function send_notification($registatoin_ids, $message) {
        // include config
        include_once './config.php';

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

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

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);
        echo $result;
    }

Upvotes: 0

Views: 347

Answers (2)

abielita
abielita

Reputation: 13469

The value of delay_while_idle must be set to true. From this documentation, it states that if the device is connected but idle, the message will still be delivered right away unless the delay_while_idle flag is set to true.

This can also be a TCP timeout and Android have a mechanism to send a little network packet (called heartbeat) every x minutes to avoid the tcp connection timeout and check if the connection is alive. You may check this forum that explains the issue.

Upvotes: 1

Gavriel
Gavriel

Reputation: 19237

The only way I know to change the behaviour is to set the delay_while_idle to true or false and to change the time_to_live. For example by setting delay_while_idle = false, time_to_leave = 0 Google will try to deliver the messages ASAP, however ttl=0 also means that messages that can't be sent immediately (let's say the user is in an area out of network) will most probably be lost.

What I do in my app is I send 2 messages with the same ID. One with ttl=0, so it tries to deliver it immediately, and another with ttl=20minutes. This way even if late some of those messages are also being delivered. I am not sure if this makes sense in your case.

Upvotes: 2

Related Questions