0

Hello everyone I have been implementing gcm but the problem is that it is not receiving the notification and I have tried both sending gcm message from my project web server and tried to implement it on android but still it doesn't worked, it is generating the token id properly but it doesn't receive any message , following is my classes I have used for implementing gcm

GcmServiceListner.class

public class GcmServiceListner extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
private PreferencesHandler ph;

@Override
public void onMessageSent(String msgId) {
    super.onMessageSent(msgId);
    Log.e("Anas", "MESSAGE SENT");
}

@Override
public void onMessageReceived(String from, Bundle data) {
    try {
        ph = new PreferencesHandler(this);
        int notiNum = ph.getChatNotificationNumberName();
        notiNum++;
        ph.setChatNotificationNumberName(notiNum);
        String message = data.getString("data");
        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);
    } catch (Exception e) {
        e.printStackTrace();
    }


    // [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_media_pause)
            .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());
 }
}

As you can see I have override the method of onMessageSend it calls when I have been implementing to send the message from within the app, it calls this method after few minutes when I have send the message through gcm but still onMessageReceived method doesn't works, following is the code when I m calling the send function from the app

gcm = GoogleCloudMessaging.getInstance(this);
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
           Log.e(TAG,"upstream");
            try {
                Bundle data = new Bundle();
                data.putString("data", "Hello World");

                String id = SENDING_ID;
                gcm.send(to+"@gcm.googleapis.com", id, data);
                msg = "Sent message";
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            Log.e(TAG, msg + "   msg");
        }
    }.execute();

"to" over is the token id where I have to send the message and "SENDING_ID" is the ID generated from google server

Now the following is the code of the php of my web server where I am implementing the gcm sending code

define( 'API_ACCESS_KEY', API_KEY );
    $fields = array(
        'to' => TOKEN_ID,
        'data' => "TEST MESSAGE",
    );

    $headers = array(
    'Authorization: key='.API_KEY,
        'Content-Type: application/json'                            
        );
        echo json_encode($fields);
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data

        curl_setopt($ch, CURLOPT_URL,"https://gcm-http.googleapis.com/gcm/send");

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            echo "ERROR IN CURL";
        }else{
            echo "ERROR FREE CURL";
        }

Please help me out what I have to do now :-)

EDIT MANIFEST CODE

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"></uses-permission>
<permission
    android:name="my.package.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="my.package.permission.C2D_MESSAGE" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/logo"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <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" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="my.package" />
        </intent-filter>
    </receiver>

    <service
        android:name="my.package.utility.GcmServiceListner"
        android:exported="false">

        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>
<service
        android:name="my.package.utility.MyInstanceIDListenerService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID" />
        </intent-filter>
    </service>


</application>

Anas Reza
  • 646
  • 2
  • 9
  • 28
  • have u set code in manifest file – Aditay Kaushal May 20 '16 at 07:58
  • @AditayKaushal yes I have added code in manifest let me show you the code – Anas Reza May 20 '16 at 08:00
  • check your server side responce – Aditay Kaushal May 20 '16 at 08:03
  • 1
    @noogui the solution to that thread says to simply add the uses permission with his package name. You can already see that he has that in the manifest. Did you even go through the code before suggesting a solution? Please avoid suggesting unhelpful links. – AL. May 21 '16 at 00:55
  • @AnasReza I'm not entirely sure with this, but can you try following the format of the payload in this [answer](http://stackoverflow.com/a/11253231/4625829) for your payload? This may be a long shot but I think there seems to be something wrong with payload format. Let me know of your updates. Cheers! :D – AL. May 23 '16 at 08:02

1 Answers1

0

here are my two suggestions : 1. if you are using an physical phone to test open Chrome browser and post this on the url bar chrome://inspect/#devices (this will show you if your device is connected to your PC's port).

2.On your client's side in the Upstream , you should change your code

 gcm.send(to+"@gcm.googleapis.com", id, data);

because: id is a unique msg id and should be unique every time you send a msg (otherwise it might be ignored by GCM and it will not be sent to your server)

finally your server is expecting a token ,therefore you should have a code that will extract it when the server receives a msg.(your server now is not extracting anything it can't upstream or downstream)

For now if you want to perform basic testing, you can hardcode you php , by manually copying and pasting the client's token (your phone) in TOKEN_ID and ofc your api key as well.

Pc hobbit
  • 96
  • 1
  • 11