谷歌云消息3.0设备无法接收消息

时间:2016-06-03 09:45:55

标签: google-cloud-messaging

我在链接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, “成功”:1, “失败”:0, “canonical_ids”:0 “结果”:[{ “MESSAGE_ID”: “0:1464946787970982%744ab298f9fd7ecd”}]}

我用Google搜索了很多教程,博客但我的设备仍然无法获取消息。我错过了什么吗?我的网络很好,因为我可以打开网页。

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

1 个答案:

答案 0 :(得分:0)

尝试以下解决方法:

  • 确保您已正确设置自Google收到的SENDER ID。
  • 确保您的设备已正确注册Google的GCM服务。
  • 确保您将推送发送到您从Google收到的正确注册码。并且您没有从Google GCM服务收到错误。
  • 如果您希望获得wakelock权限,则将其更改为delay_while_idle = 0。如果设置为delay_while_idle = 1,则如果设备处于空闲状态,则该消息无法到达设备。
  • 有时候推送到达需要时间(但从来没有太多时间,那就有问题)。检查&#34;生存时间&#34;你发送的推文。

您还可以查看以下相关问题: