ali
ali

Reputation: 59

how to listen for new event on server

I need to create a Listener for new events on server in android.
I was using a request to the server cyclically for new events before.

But this is not a suitable way because of performances and internet traffic.
Another way could be using a listener, but I don't know HOW TO ?

Please guide me!

Upvotes: 2

Views: 557

Answers (1)

Durai Amuthan.H
Durai Amuthan.H

Reputation: 32300

Polling the server may drain the battery

You can take advantage of Google Cloud Messaging for Android

Google Cloud Messaging (GCM) for Android is a service that allows you to send data from your server to your users' Android-powered device, and also to receive messages from devices on the same connection. The GCM service handles all aspects of queueing of messages and delivery to the target Android application running on the target device, and it is completely free.

It will work on Android >= 2.2 (on phones that have the Play Store)

Here is the link to official documentation

Here is a sample php code that sends push notification

<?php
function sendPushNotification($registration_ids, $message) {

    $url = 'https://android.googleapis.com/gcm/send';
    $fields = array(
        'registration_ids' => $registration_ids,
        'data' => $message,
    );

    define('GOOGLE_API_KEY', 'AIzaSyCjctNK2valabAWL7rWUTcoRA-UAXI_3ro');

    $headers = array(
        'Authorization:key=' . GOOGLE_API_KEY,
        'Content-Type: application/json'
    );
    echo json_encode($fields);
    $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_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    $result = curl_exec($ch);
    if($result === false)
        die('Curl failed ' . curl_error());

    curl_close($ch);
    return $result;

}
?>

Here is a good article on android push notifications

Upvotes: 2

Related Questions