Question

I am developing an android app in which i am using GCM to recieve notification from my php server and i got this response from server i-e:-

"multicast_id": 7015234441922271670,"success": 1,"failure": 0,"canonical_ids": 0,"results": [{"message_id": "0:1344007383866721%2adac3a0ad8b3148"}]

I tried almost every solution by googling but still not able to receive GCMnotification on my device, i tried conforming again and again that whether i put correct project id, Google server api key but still same problem please help me.

Mainefest

<?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 BroadCast Reciever

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 intentService

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 Code

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

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;
    }
Was it helpful?

Solution

I found out my mistake what I'm doing in my code is in GcmIntentService i comment out .setSmallIcon(R.drawable.ic_stat_gcm) so that's the reason even after receiving message i was not able to see the notification.

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        //.setSmallIcon(R.drawable.ic_stat_gcm)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top