无法接收 GCM 通知?

Posted

技术标签:

【中文标题】无法接收 GCM 通知?【英文标题】:Unable to receive GCM notification? 【发布时间】:2014-05-04 14:33:53 【问题描述】:

我正在开发一个 android 应用程序,在该应用程序中我使用 GCM 从我的 php 服务器接收通知,并且我从服务器 i-e 得到了这个响应:-

“multicast_id”:7015234441922271670,“成功”:1,“失败”: 0,"canonical_ids": 0,"results": ["message_id": "0:1344007383866721%2adac3a0ad8b3148"]

我通过谷歌搜索尝试了几乎所有解决方案,但仍然无法在我的设备上接收GCMnotification,我尝试一次又一次地确认我是否输入了正确的项目 ID、Google 服务器 api 密钥但仍然存在同样的问题,请帮助我。

缅因州

<?xml version="1.0" encoding="UTF-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.informaluser.eaas"
    android:versionCode="1"
    android:versionName="1.0" >

     <permission
        android:name="com.informaluser.eaas.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

     <permission
        android:name="com.informaluser.eaas.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

     <uses-permission android:name="com.informaluser.eaas.permission.C2D_MESSAGE" />
     <uses-permission android:name="com.informaluser.eaas.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.informaluser.eaas.Login"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


        <activity android:name="com.informaluser.eaas.Map"
                  android:label="Map of EAAS"></activity>

        <receiver
            android:name="com.informaluser.eaas.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="com.informaluser.eaas" />
            </intent-filter>
        </receiver>

        <service android:name="com.informaluser.eaas.GcmIntentService" />

    <!-- Google Maps API Key -->
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="My key" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

</application>

GCM 广播接收器

package com.informaluser.eaas;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver

    @Override
    public void onReceive(Context context, Intent intent) 
        // TODO Auto-generated method stub

        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);


    


GCM 意图服务

package com.informaluser.eaas;

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

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class GcmIntentService extends IntentService
    Context context;
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    public static final String TAG = "GCM Demo";

    public GcmIntentService() 
        super("GcmIntentService");
        // TODO Auto-generated constructor stub
    

    @Override
    protected void onHandleIntent(Intent intent) 
        // TODO Auto-generated method stub
        Bundle extras = intent.getExtras();
        String msg = intent.getStringExtra("message");
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

         if (!extras.isEmpty()) 

             if (GoogleCloudMessaging.
                        MESSAGE_TYPE_SEND_ERROR.equals(messageType)) 
                    sendNotification("Send error: " + extras.toString());
                 else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_DELETED.equals(messageType)) 
                    sendNotification("Deleted messages on server: " +
                            extras.toString());
                // If it's a regular GCM message, do some work.
                 else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_MESSAGE.equals(messageType)) 
                    // This loop represents the service doing some work.
                    for (int i=0; i<5; i++) 
                        Log.i(TAG, "Working... " + (i+1)
                                + "/5 @ " + SystemClock.elapsedRealtime());
                        try 
                            Thread.sleep(500);
                         catch (InterruptedException e) 
                        
                    
                    Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                    // Post notification of received message.
                    //sendNotification("Received: " + extras.toString());
                    sendNotification(msg);
                    Log.i(TAG, "Received: " + extras.toString());
                
            
         GcmBroadcastReceiver.completeWakefulIntent(intent);
    
    private void sendNotification(String msg) 
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent myintent = new Intent(this, Map.class);
        myintent.putExtra("message", msg);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                myintent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        //.setSmallIcon(R.drawable.ic_stat_gcm)
        .setContentTitle("GCM Notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    


PHP 代码

else if ($tag == 'msgsend') 

    $msg = $_POST['msg'];

    $reg = array("APA91bEk8ONc-En6wFZ6nawReKl-5xlTiRy9OOYx8731wnG0Cdp7EBqlwqguK_m3q-rCSytiEzukEMoOued_Nzb2UPPn4z46N4HuG6j93Jqbx47XwA");

            $notify = $db->send_push_notification($reg,$msg);
          if($notify!=false)

            $response["success"] = 1;
            $response["user"]["msg"] = $user["msg"];
            echo json_encode($response);
            
        else 

            $response["error"] = 1;
            $response["error_msg"] = "JSON Error occured";
            echo json_encode($response);
        
    

send_push_notification 函数

function send_push_notification($registatoin_ids, $message) 


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

        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => array("message" => $message),
        );
        // Google Cloud Messaging GCM API Key
        define("GOOGLE_API_KEY", "My Google Console Server Key");

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        //print_r($headers);
        // 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);
        return $result;
        if ($result === FALSE) 
            die('Curl failed: ' . curl_error($ch));

        

        // Close connection
        curl_close($ch);
        echo $result;
        return $result;
    

【问题讨论】:

您在发送消息时是否在 logcat 中看到任何内容? @Eran 是的 "multicast_id":4789513855634684706,"success":1,"failure":0,"canonical_ids":0,"results":["message_id":"0: 1399217879762829%f9286410f9fd7ecd"] 不,这是您在服务器上得到的响应。您应该在您的 android 设备连接到计算机时发送消息,并查看设备日志中是否有任何内容。 @Eran 当我发送消息时我在设备日志中没有得到响应 @Eran 现在我检查了我在我的设备上收到此响应,但没有出现通知“I/GCM Demo(1518): Working... 1/5 @ 1230455 I/GCM Demo(1518) : 工作... 2/5 @ 1230958 I/GCM 演示(1518): 工作... 3/5 @ 1231459 I/GCM 演示(1518): 工作... 4/5 @ 1231961 I/GCM 演示(1518 ): 工作... 5/5 @ 1232463 I/GCM Demo(1518): 已完成工作 @ 1232964 I/GCM Demo(1518): 0.0 I/GCM Demo(1518): 收到: Bundle[message=0.0, android .support.content.wakelockid=1, collapse_key=do_not_collapse, from=31292454533]" 【参考方案1】:

我发现我在代码中所做的错误是在GcmIntentService 我注释掉.setSmallIcon(R.drawable.ic_stat_gcm) 所以这就是即使在收到消息后我也看不到通知的原因。

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        //.setSmallIcon(R.drawable.ic_stat_gcm)

【讨论】:

以上是关于无法接收 GCM 通知?的主要内容,如果未能解决你的问题,请参考以下文章

接收 GCM 时出现错误消息

仅接收来自 GCM 的最后一个后台静默推送通知

当应用程序关闭时,GCM 广播接收器未检测到 gcm 通知

设备如何接收 Android GCM 推送通知?

是否可以在 Android 模拟器中接收 GCM 通知?

Google GCM - 未在 android Lollipop 中接收推送通知