【问题标题】:google cloud message 3.0 device not receive message谷歌云消息3.0设备收不到消息
【发布时间】:2016-10-03 07:46:03
【问题描述】:

我按照链接https://developers.google.com/cloud-messaging/android/client中的“快速入门示例”和google云消息最新版本的说明,并从此说明下载项目。我成功获取了设备的令牌,并且我有一个 php 服务器要发送到谷歌云,但我无法从我的设备获取消息。你能帮帮我吗。

我从这个网站下载了上面这个链接中推荐的项目

$ git clone https://github.com/googlesamples/google-services.git

下面是我的服务器代码

gcm.php

 // Payload data you want to send to Android device(s)
        // (it will be accessible via intent extras)    
        $data = array('message' => 'Hello World!');

        // The recipient registration tokens for this notification
        // https://developer.android.com/google/gcm/  

        $ids = array('foD2qlwvb9U:APA91bGOD6VD8GxGtZXmg-oFwDElMCXNOxptLXvNL3NHzKenwUYKzUFUbIapBhuuOW2ee8oC3ZUPdGRcjmOrA5B4zrzG_UQtj7soqjisM4NUHe4L4IfSjoWRiXKJfQ_918XDgX11hWdT');

        // Send push notification via Google Cloud Messaging
        sendPushNotification($data, $ids);

        function sendPushNotification($data, $ids)
        {
            // Insert real GCM API key from the Google APIs Console
            // https://code.google.com/apis/console/            

            // Set POST request body
            $post = array(
                            'registration_ids'  => $ids,
                            'data'              => $data,
                         );

            // Set CURL request headers 
            $headers = array( 
                                'Authorization: key=AIzaSyCGw1NOaemsZWUFbUWcLCPP5p_Kcvmc9mg',
                                'Content-Type: application/json'
                            );

            // Initialize curl handle       
            $ch = curl_init();

            // Set URL to GCM push endpoint     
            //curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
            curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');

            // Set request method to POST       
            curl_setopt($ch, CURLOPT_POST, true);

            // Set custom request headers       
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // Get the response back as string instead of printing it       
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Set JSON post data
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));

            // Actually send the request    
            $result = curl_exec($ch);

            // Handle errors
            if (curl_errno($ch))
            {
                echo 'GCM error: ' . curl_error($ch);
            }

            // Close curl handle
            curl_close($ch);

            // Debug GCM response       
            echo $result;


        }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="gcm.play.android.samples.com.gcmquickstart" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
    <!-- [START gcm_permission] -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />


    <permission android:name="gcm.play.android.samples.com.gcmquickstart.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="gcm.play.android.samples.com.gcmquickstart.permission.C2D_MESSAGE" />

    <!-- 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" />
    <!-- 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" />

    <!-- [END gcm_permission] -->

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="gcm.play.android.samples.com.gcmquickstart.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- [START gcm_receiver] -->
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="gcm.play.android.samples.com.gcmquickstart" />

            </intent-filter>
        </receiver>
        <!-- [END gcm_receiver] -->

        <!-- [START gcm_listener] -->
        <service
            android:name="gcm.play.android.samples.com.gcmquickstart.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <!-- [END gcm_listener] -->
        <!-- [START instanceId_listener] -->
        <service
            android:name="gcm.play.android.samples.com.gcmquickstart.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>
        <!-- [END instanceId_listener] -->
        <service
            android:name="gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService"
            android:exported="false">
        </service>
    </application>

</manifest>

MyGcmListenerService.java

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) {
        Log.d(TAG, "onMessageReceived");
        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.ic_stat_ic_notification)
                .setContentTitle("GCM Message")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

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

我收到了来自服务器的消息:

{"multicast_id":5585998123799628757,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1464946787970982%744ab298f9fd7ecd"}]}

我在谷歌上搜索了很多教程、博客,但我的设备仍然无法收到消息。我错过了什么吗?我的网络很好,因为我可以打开网页。

已解决:我更改为 Firebase 云消息并且它可以工作。 感谢所有在这里帮助我的朋友。

【问题讨论】:

  • 由于您收到成功响应,因此问题可能出在客户端 (Android) 端。您能否将 MyGcmListenerService 的实现添加到您的问题中?
  • 后端代码似乎没问题。如果我是对的,您正在使用模板。我在这个问题上支持亚瑟。它可能与您的 GCMListenerService
  • 亲爱的@Arthur Thompson 我编辑了我的帖子,添加了 MyGcmListenerService.java 代码。感谢您的回复
  • 亲爱的@McAwesomville 我编辑了我的帖子,添加了 MyGcmListenerService.java 代码。感谢您的回复
  • onMessageReceived 是否被调用过?您在 logcat 中看到“from”和“message”的日志消息了吗?

标签: google-cloud-messaging


【解决方案1】:

尝试以下解决方法:

  • 确保您正确设置了从 Google 收到的 SENDER ID。
  • 确保您的设备已正确注册到 Google 的 GCM 服务。
  • 确保将推送发送到您从 Google 收到的正确 reg id。并且您没有收到来自 Google GCM 服务的错​​误消息。
  • 如果您希望您的唤醒锁定权限有所作为,请将其更改为 delay_while_idle = 0。如果设置为delay_while_idle = 1,则消息在空闲时不会到达设备。
  • 有时推送到达需要一些时间(但永远不会有太多时间,那么就会出现问题)。检查您发送的推送的“生存时间”。

您还可以查看这些相关问题:

【讨论】:

  • 亲爱的@abielita,“SENDER ID”是“Credentials”中的服务器密钥吗?我的设备向 GCM 注册,因为我可以使用 logcat 从 GCM 获取令牌密钥响应。我在公司使用我的设备 NovaP 进行测试,但是当我使用另一个网络设置去另一个地方时,我的设备可以从 GCM 获取之前发送的消息。我认为问题可能来自网络设置。
  • 我听说我们需要允许端口 5228 。这样对吗 ?如果这是正确的,我该怎么做才能允许端口 5228。如果另一个网络设置不允许端口 5228 会发生什么?我们如何在任何地方都使用 GCM?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 2013-10-04
  • 2016-04-21
相关资源
最近更新 更多