如何从php向安卓发送通知?

2022-08-30 20:39:15

我使用php和mysql开发了一个网站。我想为上传到我的网站的每个帖子向Android设备发送通知。

是否可以使用GCM服务器发送通知?如果是,那么我如何向所有安装了Android应用程序的设备发送通知?


答案 1

我决定为我自己的问题发布答案

现在谷歌推出了FCM

<?php
define('API_ACCESS_KEY','Api key from Fcm add here');
 $fcmUrl = 'https://fcm.googleapis.com/fcm/send';
 $token='235zgagasd634sdgds46436';

    $notification = [
            'title' =>'title',
            'body' => 'body of message.',
            'icon' =>'myIcon', 
            'sound' => 'mySound'
        ];
        $extraNotificationData = ["message" => $notification,"moredata" =>'dd'];

        $fcmNotification = [
            //'registration_ids' => $tokenList, //multple token array
            'to'        => $token, //single token
            'notification' => $notification,
            'data' => $extraNotificationData
        ];

        $headers = [
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        ];


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$fcmUrl);
        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($fcmNotification));
        $result = curl_exec($ch);
        curl_close($ch);


        echo $result;

答案 2

首先,遵循实现GCM客户端并在Android应用程序中实现gcm客户端。

对于php中的GCM服务器,您可以通过以下方式实现它。根据需要编辑您的代码,例如发布帖子时的代码。有关实施 GCM 服务器的更多信息,请转到实施 GCM 服务器

<?php
    // Replace with the real server API key from Google APIs
    $apiKey = "your api key";

    // Replace with the real client registration IDs
    $registrationIDs = array( "reg id1","reg id2");

    // Message to be sent
    $message = "Your message e.g. the title of post";

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

    $fields = array(
        'registration_ids' => $registrationIDs,
        'data' => array( "message" => $message ),
    );
    $headers = array(
        'Authorization: key=' . $apiKey,
        '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);
    //curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_POST, true);
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

    // Execute post
    $result = curl_exec($ch);

    // Close connection
    curl_close($ch);
    // print the result if you really need to print else neglate thi
    echo $result;
    //print_r($result);
    //var_dump($result);
?>

还有一个很好的帖子 Android 推送通知 适合初学者。


推荐