2016-02-08 63 views
-1

当我通过php文件提交数据时,它向注册手机发送通知,但是没有消息内容的空消息。尽量尝试在线提供所有教程,但没有获得它。请帮助。GCM推送通知即将到来但带有空消息

服务器端代码:PHP文件

<?php 
$con = mysql_connect("localhost", "umane", "pass"); 
if(!$con){ 
die('MySQL connection failed'); 
} 

$db = mysql_select_db("dbname"); 
if(!$db){ 
die('Database selection failed'); 
} 

$registatoin_ids = array(); 
$sql = "SELECT * FROM tblname"; 
$result = mysql_query($sql, $con); 
while($row = mysql_fetch_assoc($result)){ 
array_push($registatoin_ids, $row['registration_id']); 

} 

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

$message = array("Notice" => $_POST['message']); 
$fields = array(
'registration_ids' => $registatoin_ids, 
'data' => $message, 
); 

$headers = array(
'Authorization: key= MY 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; 
?> 

的Android代码:

public class GcmSender { 

    public static final String API_KEY = "My API KEY"; 

    public static void main(String[] args) { 
     if (args.length < 1 || args.length > 2 || args[0] == null) { 
      System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); 
      System.err.println(""); 
      System.err.println("Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + 
        "specified, the message will only be sent to that device. Otherwise, the message \n" + 
        "will be sent to all devices subscribed to the \"global\" topic."); 
      System.err.println(""); 
      System.err.println("Example (Broadcast):\n" + 
        "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + 
        "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); 
      System.err.println(""); 
      System.err.println("Example (Unicast):\n" + 
        "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + 
        "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); 
      System.exit(1); 
     } 
     try { 
      // Prepare JSON containing the GCM message content. What to send and where to send. 
      JSONObject jGcmData = new JSONObject(); 
      JSONObject jData = new JSONObject(); 
      jData.put("data", args[0].trim()); 
      // Where to send GCM message. 
      if (args.length > 1 && args[1] != null) { 
       jGcmData.put("registration_ids", args[1].trim()); 
      } else { 
       jGcmData.put("registration_ids", "/topics/global"); 
      } 
      // What to send in GCM message. 
      jGcmData.put("data", jData); 

      // Create connection to send GCM Message request. 
      URL url = new URL("https://android.googleapis.com/gcm/send"); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestProperty("Authorization", "key=" + API_KEY); 
      conn.setRequestProperty("Content-Type", "application/json"); 
      conn.setRequestMethod("POST"); 
      conn.setDoOutput(true); 

      // Send GCM message content. 
      OutputStream outputStream = conn.getOutputStream(); 
      outputStream.write(jGcmData.toString().getBytes()); 

      // Read GCM response. 
      InputStream inputStream = conn.getInputStream(); 
      String resp = IOUtils.toString(inputStream); 
      System.out.println(resp); 
      System.out.println("Check your device/emulator for notification or logcat for " + 
        "confirmation of the receipt of the GCM message."); 
     } catch (IOException e) { 
      System.out.println("Unable to send GCM message."); 
      System.out.println("Please ensure that API_KEY has been replaced by the server " + 
        "API key, and that the device's registration token is correct (if specified)."); 
      e.printStackTrace(); 
     } 
    } 

} 

接收器代码

/** 
* Copyright 2015 Google Inc. All Rights Reserved. 
* 
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed under the License is distributed on an "AS IS" BASIS, 
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License. 
*/ 

package gcm.play.android.samples.com.gcmquickstart; 

import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.media.RingtoneManager; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.NotificationCompat; 
import android.util.Log; 

import com.google.android.gms.gcm.GcmListenerService; 

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 

    /** 
    * Called when message is received. 
    * 
    * @param from SenderID of the sender. 
    * @param data Data bundle containing message data as key/value pairs. 
    *    For Set of keys use data.keySet(). 
    */ 
    // [START receive_message] 
    @Override 
    public void onMessageReceived(String from, Bundle data) { 
     String message = data.getString("data"); 
     Log.d(TAG, "From: " + from); 
     Log.d(TAG, "Message: " + message); 

     if (from.startsWith("/topics/")) { 
      // message received from some topic. 
     } else { 
      // normal downstream message. 
     } 

     // [START_EXCLUDE] 
     /** 
     * Production applications would usually process the message here. 
     * Eg: - Syncing with server. 
     *  - Store message in local database. 
     *  - Update UI. 
     */ 

     /** 
     * In some cases it may be useful to show a notification indicating to the user 
     * that a message was received. 
     */ 
     sendNotification(message); 
     // [END_EXCLUDE] 
    } 
    // [END receive_message] 

    /** 
    * Create and show a simple notification containing the received GCM message. 
    * 
    * @param message GCM message received. 
    */ 
    private void sendNotification(String message) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.ic_stat_ic_notification) 
       .setContentTitle("E Protocol") 
       .setContentText(message) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
} 
+1

你在哪里定义接收器在Android将接收GCM消息...? – koutuk

+0

你可以关注这个tut [链接](http://androidexample.com/Android_Push_Notifications_using_Google_Cloud_Messaging_GCM/index.php?view=article_discription&aid=119&aaid=139) –

+0

@koutuk我已经添加了接收者的代码 –

回答

1

你确信它检索在你的PHP代码中的POST变量? 尝试更换此:

$message = array("Notice" => $_POST['message']); 

有:

$message = array("Notice" => "testing"); 

此外,在接收机你说

String message = data.getString("data"); 

但你在PHP代码中定义的数据作为 “通知”,所以要检索您必须说的数据:

String message = data.getString("Notice"); 
+0

谢谢..它完美的作品: ) –