android - GCM - 为什么我在 onMessageReceived 中得到 NULL?

标签 android google-cloud-messaging

我正在使用谷歌云消息传递,并且我成功发送了推送通知。我遇到的唯一问题是 onMessageReceived 方法总是为空。 我可以通过日志告诉我,它显示为空。我从服务器发送给用户,这就是我得到的


例如 04-16 12:29:17.231 19637-19705/com.world.bolandian.watchme
D/MyGcmListenerService: 消息: null

这是我的服务器代码

 package jdbc;

 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;

 import javax.sound.midi.SysexMessage;

 import com.google.android.gcm.server.Message;
 import com.google.android.gcm.server.Result;
 import com.google.android.gcm.server.Sender;

 public class GcmSender {
    private static final int GCM_RETRIES = 2;

  public void sendGooglePushNotification(String token, String type, String data, String serverApiKey) {

    // Create Message
    Message.Builder builder = new Message.Builder().delayWhileIdle(true);

    try {
        builder.addData(Params.TYPE_MESSAGE, URLEncoder.encode(type, "UTF-8"));
        builder.addData(Params.DATA_MESSAGE, URLEncoder.encode(data, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Message message = builder.build();

    // Create Sender
    Sender sender = new Sender(serverApiKey);

    // Sending Message with Sender to the list of users.
    try {

        Result rs=sender.send(message, token, GCM_RETRIES);
        String ans=rs.toString();
        System.out.println(ans);

        //System.out.println("notification sent");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        // Failed to Send Message.

        }

    }
 }

这是安卓代码

 package com.world.bolandian.watchme;

 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("message");
    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.common_google_signin_btn_icon_dark)
            .setContentTitle("ALERT")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =

            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

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

我确实收到了 GCM 消息,但没有从服务器发送的消息(数据)。并在日志上显示为空。 你们知道如何解决这个问题吗?

最佳答案

Message.Builder builder = new Message.Builder().addData("message", "Your string here").delayWhileIdle(true);

Message message = new Message.Builder().addData("message", "Your string here").delayWhileIdle(true).build();

在服务器端,您需要向消息中添加数据,您应该使用键和值添加数据,然后您将像那样在 android 中获取它,在您的代码中,您等待来自 android 中键“消息”的数据,而不是从服务器

关于android - GCM - 为什么我在 onMessageReceived 中得到 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36665134/

相关文章:

android - 使用标准 Activity 创建预填充联系人

android - 当手机处于休眠状态或 Activity (用于启动服务)未运行时,服务不应停止

java - Activity 类中的静态字段是否保证比创建/销毁周期更长?

android - GCM(Google Cloud Messaging)在android编程中是否比Web服务通信有任何优势

android - 无法通过 Facebook Android SDK 获取电子邮件地址

java - 链接回亚马逊应用商店以获取评分

android - 在 cordova 插件中获取上下文

android - GCM 错误 - googleCloudMessaging.register

android - GCM 通知的自定义 UI

android - 通过 GCM 的 Worklight 6.3 推送通知无法到达 Android 设备