GCM推送通知即将到来,但有空消息 [英] GCM push notification coming but with empty message

查看:249
本文介绍了GCM推送通知即将到来,但有空消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



服务器端代码: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']);

}

//设置POST变量
$ 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'
);
//打开连接
$ ch = curl_init();

//设置网址,POST变量的数量,POST数据
curl_setopt($ ch,CURLOPT_URL,$ url);

curl_setopt($ ch,CURLOPT_POST,true);
curl_setopt($ ch,CURLOPT_HTTPHEADER,$ headers);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);

//临时禁用SSL证书支持
curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);

curl_setopt($ ch,CURLOPT_POSTFIELDS,json_encode($ fields));

//执行后
$结果= curl_exec($ ch);
if($ result === FALSE){
die('Curl failed:'。curl_error($ ch));
}
//关闭连接
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(指定要通过GCM广播的测试消息,如果设备的GCM注册令牌是\+
,则只会将消息发送到该设备,否则,消息\\\
+
将被发送到订阅了\global \主题的所有设备。);
System.err.println();
System.err.println(Example(Broadcast):\\\
+
在Windows上:.\\gradlew.bat运行-Pmsg = \< Your_Message> \ \\\
+
在Linux / Mac上:./gradlew run -Pmsg = \< Your_Message> \);
System.err.println();
System.err.println(Example(Unicast):\\\
+
在Windows上:.\\gradlew.bat运行-Pmsg = \< Your_Message> \ -Pto = \< Your_Token> \\\\
+
在Linux / Mac上:./gradlew run -Pmsg = \< Your_Message> \-Pto = \\ \\ < Your_Token> \);
System.exit(1);
}
尝试{
//准备包含GCM消息内容的JSON。发送内容和发送地点。
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put(data,args [0] .trim());
//在哪里发送GCM消息。
if(args.length> 1&& args [1]!= null){
jGcmData.put(registration_ids,args [1] .trim());
} else {
jGcmData.put(registration_ids,/ topics / global);
}
//在GCM消息中发送什么。
jGcmData.put(data,jData);

//创建连接发送GCM消息请求。
网址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);

//发送GCM信息内容。
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString()。getBytes());

//读取GCM响应。
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
System.out.println(请检查您的设备/仿真程序是否有通知,logcat是否为+
确认收到GCM消息。);
} catch(IOException e){
System.out.println(Unable to send GCM message。);
System.out.println(请确保API_KEY已被服务器替换为+
API密钥,并且设备的注册令牌是正确的(如果指定)。
e.printStackTrace();
}
}

}

接收者代码

  / ** 
*版权所有2015 Google Inc.保留所有权利。
*
*根据Apache许可证2.0版许可(许可证);
*除遵守许可证外,您不得使用此文件。
*您可以在
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*获得许可证副本根据适用法律要求或书面同意,根据许可分配的软件
*以原样基础,
*分发,不附有任何明示或暗示的担保或条件。
*请参阅许可证以了解许可证下特定语言的管理权限和
*限制。
* /

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

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

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

public class MyGcmListenerService extends GcmListenerService {

private static final String TAG =MyGcmListenerService;

/ **
*收到消息时调用。
*
* @param from SenderID of sender。
* @param data包含消息数据作为键/值对的数据包。
*对于密钥集使用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 /)){
//从某个主题收到的消息。
} else {
//正常的下行消息。
}

// [START_EXCLUDE]
/ **
*生产应用程序通常会在此处理消息。
*例如: - 与服务器同步。
* - 将消息存储在本地数据库中。
* - 更新用户界面。
* /

/ **
*在某些情况下,显示向用户显示收到消息的通知
*会很有用。
* /
sendNotification(message);
// [END_EXCLUDE]
}
// [END receive_message]

/ **
*创建并显示包含接收到的GCM的简单通知信息。
*
* @参数消息收到GCM消息。
* /
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 * /,notificationBuilder.build());



$ div $解析方案

你确定它在您的PHP代码中检索POST变量?
尝试将其替换:

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

附带:

  $ message = array(Notice=>testing); 

同样在你的接收器中,你说的是

  String message = data.getString(data); 

但是您在php代码中将数据定义为Notice,因此要检索必须的数据说:

  String message = data.getString(Notice); 


When I submit data through php file it is giving notification to registered phone but there is an empty message only no message content.Mostly tried all tutorial available online but not getting it.Please help.

Server Side Code:php file

<?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 Code:

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();
        }
    }

}

Receiver Code

/**
 * 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());
    }
}

解决方案

You are certain that it's retrieving the POST variable in your PHP code? Try to replace this:

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

with:

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

Also in your receiver you are saying

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

But you defined your data as "Notice" in the php code, so to retrieve the data you must say:

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

这篇关于GCM推送通知即将到来,但有空消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆