Push Notification Android con GCM, PHP e MySQL

? user3091035 @ | Original: StackOverFlow
---

Sto avendo edizione con notifiche push . Sto cercando Notifiche push Android utilizzando Google Cloud Messaging ( GCM ), PHP e MySQL seguendo le istruzioni di cui al AndroidHive . Il dispositivo è iscritto GCM e può vedere il record nel database tuttavia quando inviare notifica push, non in grado di ricevere sul dispositivo . Vi metto il link che ho seguito . Si prega di avvisare se mi manca nulla . http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

Manifest file:

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.pushnotifications"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- GCM requires Android SDK version 2.2 (API level 8) or above. -->
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <!-- GCM connects to Internet Services. -->
    <uses-permission android:name="android.permission.INTERNET" />

    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- Creates a custom permission so only this app can receive its messages. -->
    <permission
        android:name="com.androidhive.pushnotifications.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.androidhive.pushnotifications.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <!-- Network State Permissions to detect Internet status -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <!-- Permission to vibrate -->
    <uses-permission android:name="android.permission.VIBRATE" />

    <!-- Main activity. -->
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <!-- Register Activity -->
        <activity
            android:name=".RegisterActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Main Activity -->
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name" >
        </activity>

        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <!-- Receives the registration id. -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.androidhive.pushnotifications" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
    </application>

</manifest>


index.php

index.php
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){

            });
            function sendPushNotification(id){
                var data = $('form#'+id).serialize();
                $('form#'+id).unbind('submit');               
                $.ajax({
                    url: "send_message.php",
                    type: 'GET',
                    data: data,
                    beforeSend: function() {

                    },
                    success: function(data, textStatus, xhr) {
                          $('.txt_message').val("");
                    },
                    error: function(xhr, textStatus, errorThrown) {

                    }
                });
                return false;
            }
        </script>
        <style type="text/css">
            .container{
                width: 950px;
                margin: 0 auto;
                padding: 0;
            }
            h1{
                font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
                font-size: 24px;
                color: #777;
            }
            div.clear{
                clear: both;
            }
            ul.devices{
                margin: 0;
                padding: 0;
            }
            ul.devices li{
                float: left;
                list-style: none;
                border: 1px solid #dedede;
                padding: 10px;
                margin: 0 15px 25px 0;
                border-radius: 3px;
                -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
                -moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
                box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
                font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
                color: #555;
            }
            ul.devices li label, ul.devices li span{
                font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
                font-size: 12px;
                font-style: normal;
                font-variant: normal;
                font-weight: bold;
                color: #393939;
                display: block;
                float: left;
            }
            ul.devices li label{
                height: 25px;
                width: 50px;               
            }
            ul.devices li textarea{
                float: left;
                resize: none;
            }
            ul.devices li .send_btn{
                background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
                background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
                background: -moz-linear-gradient(center top, #0096FF, #005DFF);
                background: linear-gradient(#0096FF, #005DFF);
                text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
                border-radius: 3px;
                color: #fff;
            }
        </style>
    </head>
    <body>
        <?php
        include_once 'db_functions.php';
        $db = new DB_Functions();
        $users = $db->getAllUsers();
        if ($users != false)
            $no_of_users = mysql_num_rows($users);
        else
            $no_of_users = 0;
        ?>
        <div class="container">
            <h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
            <hr/>
            <ul class="devices">
                <?php
                if ($no_of_users > 0) {
                    ?>
                    <?php
                    while ($row = mysql_fetch_array($users)) {
                        ?>
                        <li>
                            <form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
                                <label>Name: </label> <span><?php echo $row["name"] ?></span>
                                <div class="clear"></div>
                                <label>Email:</label> <span><?php echo $row["email"] ?></span>
                                <div class="clear"></div>
                                <div class="send_container">                               
                                    <textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
                                    <input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
                                    <input type="submit" class="send_btn" value="Send" onclick=""/>
                                </div>
                            </form>
                        </li>
                    <?php }
                } else { ?>
                    <li>
                        No Users Registered Yet!
                    </li>
                <?php } ?>
            </ul>
        </div>
    </body>
</html>

Register.php

<?php

// response json
$json = array();

/**
 * Registering a user device
 * Store reg id in users table
 */
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $gcm_regid = $_POST["regId"]; // GCM Registration ID
    // Store user details in db
    include_once './db_functions.php';
    include_once './GCM.php';

    $db = new DB_Functions();
    $gcm = new GCM();

    $res = $db->storeUser($name, $email, $gcm_regid);

    $registatoin_ids = array($gcm_regid);
    $message = array("product" => "shirt");

    $result = $gcm->send_notification($registatoin_ids, $message);
    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        'Content-Type: application/json'
    );

    echo $result;
} else {
    // user details missing
}
?>
---

Top 5 Risposta

1Sachin Shelke @

Ho anche affrontato lo stesso problema quando stavo cercando di implementare notifica push con link qui sopra . Dopo qualche giorno nonsense R & amp ; D ho raggiunto a soluzione che fornisco la chiave sbagliata google nel codice php . Mi stavo qualche errore 404 di stato.

Quindi la soluzione è

Login in to Google Console Account https://console.developers.google.com Create new Project Under APIs & Auth-> select API and enable Google Cloud Messaging for Android services Then under APIs & Auth -> select "Credentials"-> "Create New Key" in Public API access section Select "Browser Key" under "Create New Key" dialog. and again click "Create" (without adding anything in textarea) It will get new API key.

Copia questa chiave api incollarlo in codice register.php .

 $headers = array(
        'Authorization: key=' . 'AIzaSyDa4aTJMblZixlatAZjdDXxCf_2mJqc3WM', // HERE IT IS DEMO KEY
        'Content-Type: application/json'
    );

Ora si può provare l'invio di notifica . Dovrebbe funzionare .

Godetevi ... Happy Coding .

2Charly @

Ecco uno script di lavoro

<?php

class GCM {

//put your code here
// constructor
function __construct() {

}
/**
 * Sending Push Notification
 */
static function send_notification($data=array()) {

// Set POST variables
$ = 'https://android.googleapis.com/gcm/send';
$apiKey = 'API key register via google console';
$data = array(
        'registration_ids' => array($data['device_token']),
        'data' =>array("message"=>$data['message'])
    ); 


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

    $ch = curl_init();

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

    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($data));
            //echo json_encode($data);
    // Execute post
    $result = curl_exec($ch);

    if ($result === FALSE) {

        die('Curl failed: ' . curl_error($ch));
    }
    print_r($result);
    // Close connection
    curl_close($ch);

}
}

Ecco 2 IMP cose da considerare

1) API KEY che è registrato tramite console google deve essere valido .

2 ) segno dispositivo di dispositivo Android in cui sarà ricevuto spinta