如何监听服务器上的新事件

how to listen for new event on server

我需要为 android 服务器上的新事件创建一个侦听器。
我之前一直在为新事件周期性地向服务器发出请求。

但由于性能和互联网流量,这不是一个合适的方式。
另一种方法是使用监听器,但我不知道 HOW TO

请指导!

轮询服务器可能会耗尽电池电量

您可以利用 Google 云消息 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.

它适用于 Android >= 2.2(在有 Play 商店的手机上)

这里是link官方文档

这是发送推送通知的示例php代码

<?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;

}
?>

这是 android 推送通知good article